NSLayoutConstraint 和 safeAreaLayoutGuide - 编码兼容 pre-iOS 11

NSLayoutConstraint and safeAreaLayoutGuide - coding compatible for pre-iOS 11

如果我想要一个与 pre-iOS 11 设备兼容的应用程序,我是否需要为将视图的某些 属性 链接到 self.view 中的每个约束使用此代码为了遵守safeAreaLayoutGuide?

if #available(iOS 11.0, *) {
     NSLayoutConstraint.activate([
          theImage.heightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor, multiplier: 0.5)
          theImage.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20),
          theImage.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -view.frame.width/8)
     ])
} else {
     NSLayoutConstraint.activate([
          theImage.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5)
          theImage.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
          theImage.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -view.frame.width/8),
     ])
}

该代码看起来正确。如果您担心到处都是重复的内容,可以通过多种方式对其进行整合。你可以这样做:

extension UIViewController {

    var correctLayoutGuide: UILayoutGuide {
        if #available(iOS 11.0, *) {
            return view.safeAreaLayoutGuide
        }
        else {
            return view.layoutMarginsGuide
        }
    }

}

那么您的代码片段可以是:

NSLayoutConstraint.activate([
      theImage.heightAnchor.constraint(equalTo: correctLayoutGuide.heightAnchor, multiplier: 0.5)
      theImage.bottomAnchor.constraint(equalTo: correctLayoutGuide.bottomAnchor, constant: -20),
      theImage.trailingAnchor.constraint(equalTo: correctLayoutGuide.trailingAnchor, constant: 20)
 ])