最合适的方法是什么来获得不安全区域的顶部和底部高度?
当前回答
这里有一个简单的答案,可以找到所有iphone的安全区域高度
let window = UIApplication.shared.windows[0]
let SafeAreaHeight = window.safeAreaLayoutGuide.layoutFrame.size.height
其他回答
试试这个:
在Objective C中
if (@available(iOS 11.0, *)) {
UIWindow *window = UIApplication.sharedApplication.windows.firstObject;
CGFloat topPadding = window.safeAreaInsets.top;
CGFloat bottomPadding = window.safeAreaInsets.bottom;
}
在斯威夫特
if #available(iOS 11.0, *) {
let window = UIApplication.shared.keyWindow
let topPadding = window?.safeAreaInsets.top
let bottomPadding = window?.safeAreaInsets.bottom
}
在Swift - iOS 13.0及以上
//使用windows数组中的第一个元素,KeyWindow已弃用
if #available(iOS 13.0, *) {
let window = UIApplication.shared.windows.first
let topPadding = window.safeAreaInsets.top
let bottomPadding = window.safeAreaInsets.bottom
}
我正在使用CocoaPods框架和UIApplication。shared不可用,然后我在视图窗口中使用safeAreaInsets:
if #available(iOS 11.0, *) {
let insets = view.window?.safeAreaInsets
let top = insets.top
let bottom = insets.bottom
}
或者使用SwiftUI GeometryReader api。
struct V: View {
var body: some View {
GeometryReader { geometry in
Text("\(geometry.safeAreaInsets.top)")
Text("\(geometry.safeAreaInsets.bottom)")
}
}
}
代码可能不起作用,但却说明了这个想法。
objective - c 当keyWindow等于nil时谁有问题。 把上面的代码放在viewDidAppear中(不是viewDidLoad中)
要获得布局参考线之间的高度,只需这样做
let guide = view.safeAreaLayoutGuide
let height = guide.layoutFrame.size.height
所以全帧高度= 812.0,安全区高度= 734.0
下面的例子中,绿色视图的框架为guide.layoutFrame
推荐文章
- 如何在iOS中使用Swift编程segue
- Swift -整数转换为小时/分钟/秒
- 如何舍入一个双到最近的Int在迅速?
- 扁平化数组的数组在Swift
- Swift:声明一个空字典
- 为什么ARC仍然需要@autoreleasepool ?
- 在成功提交我的应用程序后,“太多符号文件”
- 从数组中随机选择一个元素
- 首先添加一个UIView,甚至是导航栏
- 我如何改变UIButton标题颜色?
- 在Swift中如何调用GCD主线程上的参数方法?
- NSLayoutConstraints是可动画的吗?
- iOS -构建失败,CocoaPods无法找到头文件
- Xcode 4挂在“附加到(应用程序名称)”
- CFNetwork SSLHandshake iOS 9失败