如果我想要一个与 iOS 11 之前的设备兼容的应用程序,我是否需要为每个将 View 的某些属性链接到 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)
])
} khác {
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
}
khác {
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)
])
Tôi là một lập trình viên xuất sắc, rất giỏi!