【问题标题】:NSLayoutConstraint and safeAreaLayoutGuide - coding compatible for pre-iOS 11NSLayoutConstraint 和 safeAreaLayoutGuide - 编码兼容 pre-iOS 11
【发布时间】:2018-02-22 21:12:06
【问题描述】:

如果我想要一个与 iOS 11 之前的设备兼容的应用程序,我是否需要此代码用于将视图的某些属性链接到 self.view 的每个约束以遵守 safeAreaLayoutGuide?​​p>

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),
     ])
}

【问题讨论】:

    标签: swift ios10 ios11 nslayoutconstraint safearealayoutguide


    【解决方案1】:

    该代码看起来正确。如果您担心到处都有重复,可以通过一些方法来整合它。你可以这样做:

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

    那么你的代码 sn-p 可能只是:

    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)
     ])
    

    【讨论】:

    • 投了赞成票。在一个更冗长的答案中间说同样的话。不要忘记扩展 UIView 的利弊。
    • 扩展看起来很棒。谢谢!关于您的“编辑”点- trailingAnchor 似乎不符合(equalTo:乘数:)。 “参数标签 '(equalTo:, multiplier:)' 不匹配任何可用的重载。”在 viewDidLoad 中运行时,此约束上的常量确实使用帧数学正确放置对象
    • 嗯,好的。如果它对您有用,请随意忽略!
    猜你喜欢
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2012-02-27
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多