如何以编程方式使用“安全区域布局"? [英] How do I use Safe Area Layout programmatically?

查看:95
本文介绍了如何以编程方式使用“安全区域布局"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我不使用情节提要来创建视图,所以我想知道是否有编程方式的使用安全区域指南"选项或类似的选项.

Since I don't use storyboards to create my views, I was wondering if there's the "Use Safe Area Guides" option programmatically or something like that.

我试图将自己的观点锚定到

I've tried to anchor my views to

view.safeAreaLayoutGuide

但它们始终与iPhone X模拟器中的顶尖重叠.

but they keep overlapping the top notch in the iPhone X simulator.

推荐答案

以下是示例代码(请参阅:安全区域布局指南):
如果您在代码中创建约束,请使用UIView的safeAreaLayoutGuide属性获取相关的布局锚点.让我们在代码中重新创建上面的Interface Builder示例,以查看其外观:

Here is sample code (Ref from: Safe Area Layout Guide):
If you create your constraints in code use the safeAreaLayoutGuide property of UIView to get the relevant layout anchors. Let’s recreate the above Interface Builder example in code to see how it looks:

假设我们在视图控制器中将绿色视图作为属性:

Assuming we have the green view as a property in our view controller:

private let greenView = UIView()

我们可能有一个函数来设置从viewDidLoad调用的视图和约束:

We might have a function to set up the views and constraints called from viewDidLoad:

private func setupView() {
  greenView.translatesAutoresizingMaskIntoConstraints = false
  greenView.backgroundColor = .green
  view.addSubview(greenView)
}

像往常一样使用根视图的layoutMarginsGuide创建前缘和尾缘约束:

Create the leading and trailing margin constraints as always using the layoutMarginsGuide of the root view:

 let margins = view.layoutMarginsGuide
 NSLayoutConstraint.activate([
    greenView.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
    greenView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
 ])

现在,除非您的目标是iOS 11及更高版本,否则您将需要使用#available来包装安全区域布局指南约束,并退回到iOS早期版本的顶部和底部布局指南:

Now, unless you are targeting iOS 11 and later, you will need to wrap the safe area layout guide constraints with #available and fall back to top and bottom layout guides for earlier iOS versions:

if #available(iOS 11, *) {
  let guide = view.safeAreaLayoutGuide
  NSLayoutConstraint.activate([
   greenView.topAnchor.constraintEqualToSystemSpacingBelow(guide.topAnchor, multiplier: 1.0),
   guide.bottomAnchor.constraintEqualToSystemSpacingBelow(greenView.bottomAnchor, multiplier: 1.0)
   ])
} else {
   let standardSpacing: CGFloat = 8.0
   NSLayoutConstraint.activate([
   greenView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: standardSpacing),
   bottomLayoutGuide.topAnchor.constraint(equalTo: greenView.bottomAnchor, constant: standardSpacing)
   ])
}

结果:


这是安全区域布局指南


安全区域是处理iPhone-X的用户界面设计所必需的.这是如何为iPhone-X设计用户界面的基本准则使用安全区域布局

这篇关于如何以编程方式使用“安全区域布局"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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