使用安全区域将元素定位到CGRect

问题描述 投票:1回答:3

我宣布一个按钮:

let button = UIButton(frame: CGRect(x: ?, y: ?, width: 50, height: 50))

但我们注意到如何设置xy相对于安全区域,以便它在>= iOS 11<= iOS 10上都很好。

我试图使用self.view.safeAreaInsets,但由于某种原因它返回0.0。任何想法如何解决这个问题?

swift ios10 ios11 safearealayoutguide
3个回答
1
投票

对于iOS 11:

如果你在self.view.safeAreaInsets上打电话,viewDidLoad, viewWillAppear, etc将为零

如果你在viewDidLayoutSubviews, viewDidAppear上调用它,它应该有值


0
投票

如果您使用自动布局和约束,这将更容易,但您可以通过这种方式获得安全区域的边距:

if #available(iOS 11.0, *) {
    if let window = UIApplication.shared.keyWindow {
        let topMargin =  window.safeAreaInsets.top
        let leftMargin =  window.safeAreaInsets.left
    }
}

0
投票

制作动画时我有同样的问题。

最后解决了问题,想法:创建一个框架相等的safeArea框架。

(仅设备方向左和右)

CGRect safeAreaFrame;

if (@available(iOS 11.0, *)) {
    UIEdgeInsets safeAreaInsets = self.view.safeAreaInsets;
    safeAreaFrame = CGRectMake(safeAreaInsets.left,
                               safeAreaInsets.top,
                               self.view.frame.size.width - safeAreaInsets.left - safeAreaInsets.right,
                               self.view.frame.size.height - safeAreaInsets.top - safeAreaInsets.bottom);
} else {

    safeAreaFrame = self.view.frame;
}

然后你有安全的区域框架使用,例如:

UIView *view = [[UIView alloc] initWithFrame:safeAreaFrame];
view.backgroundColor = UIColor.redColor;
[self.view addSubview:view];

注意:安全区域在viewDidLoad中返回(0,0,0,0),因此它们的设置晚于viewDidLoad,放入viewSafeAreaInsetsDidChange或viewDidAppear。我希望这能帮到您。

© www.soinside.com 2019 - 2024. All rights reserved.