如何找到安全区域的高度和宽度? [英] How can I find the height and width of the safe area?

查看:96
本文介绍了如何找到安全区域的高度和宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式设置相对于安全区域的高度和宽度的某些标签,按钮和文本字段的约束.例如,我希望将从标签到安全区域顶部的距离设置为安全区域高度的10%.

I'm trying programmatically set constraints for some labels, buttons, and text fields relative to the height and width of the safe area. For example, I'm hoping to set the distance from the label from the top of the safe area to 10% of the safe area's height.

如何获取安全区域的高度和宽度?

How can I retrieve the height and width of the safe area?

这是一种合理的方法吗?我的想法是,无论iOS设备如何,屏幕都会自动调整.

Is this a sound approach? My thought process was that my screen would then adjust automatically regardless of iOS device.

感谢您的帮助!

推荐答案

您可以通过存储安全区域的框架来获取高度. safeAreaLayoutGuide具有一个名为layoutFrame的属性.

You can get the height by storing the frame of the safe area. safeAreaLayoutGuide has a property named layoutFrame.

let frame = self.view.safeAreaLayoutGuide.layoutFrame
print(frame.height)
print(frame.width)

我做了一个UIView扩展,它创建了一个只读属性称为safeAreaFrame.

I made an UIView extension that creates a read-only property called safeAreaFrame.

safeAreaFrame将成为安全区域的框架.

否则,它将为bounds(仅是视图的框架).

Otherwise, it will be bounds (just the frame of the view).

extension UIView {
    public var safeAreaFrame: CGRect {
        if #available(iOS 11, *) {
            return safeAreaLayoutGuide.layoutFrame
        }
        return bounds
    }
}

示例:

let frame = self.view.safeAreaFrame 
print(frame.height)
print(frame.width)

这篇关于如何找到安全区域的高度和宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆