最合适的方法是什么来获得不安全区域的顶部和底部高度?
当前回答
对于iPhone 14设备使用如下。
let app = UIApplication.shared
var statusBarHeight: CGFloat = 0.0
let window = app.windows.filter {$0.isKeyWindow}.first
statusBarHeight = window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
let topPadding = window?.safeAreaInsets.top ?? 0.0
statusBarHeight = statusBarHeight >= topPadding ? statusBarHeight:topPadding
其他回答
要获得布局参考线之间的高度,只需这样做
let guide = view.safeAreaLayoutGuide
let height = guide.layoutFrame.size.height
所以全帧高度= 812.0,安全区高度= 734.0
下面的例子中,绿色视图的框架为guide.layoutFrame
objective - c 当keyWindow等于nil时谁有问题。 把上面的代码放在viewDidAppear中(不是viewDidLoad中)
这适用于整个视图生命周期,在Swift中是一个简单的两行解决方案:
let top = UIApplication.shared.windows[0].safeAreaInsets.top
let bottom = UIApplication.shared.windows[0].safeAreaInsets.bottom
我个人需要它在viewDidLoad和view中。safeAreaInsets还没有计算。
我正在使用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)")
}
}
}
代码可能不起作用,但却说明了这个想法。
推荐文章
- 如何删除默认的导航栏空间在SwiftUI导航视图
- 如何在iOS中使用Swift编程segue
- Swift -整数转换为小时/分钟/秒
- 如何舍入一个双到最近的Int在迅速?
- 扁平化数组的数组在Swift
- Swift:声明一个空字典
- 为什么ARC仍然需要@autoreleasepool ?
- 在成功提交我的应用程序后,“太多符号文件”
- 从数组中随机选择一个元素
- 首先添加一个UIView,甚至是导航栏
- 我如何改变UIButton标题颜色?
- 在Swift中如何调用GCD主线程上的参数方法?
- NSLayoutConstraints是可动画的吗?
- iOS -构建失败,CocoaPods无法找到头文件
- Xcode 4挂在“附加到(应用程序名称)”