我需要制作一个IBDesignable来制作一个自定义导航栏文件,该文件将根据iPhone类型调整视图的高度。如果iPhone具有像iPhone X,XR那样的顶部,则高度约束将为88,否则,对于没有顶部的iPhone 8,高度将为64。
我需要设置高度约束,而不是图层高度。这是我使用的代码,但无法更新高度约束
import UIKit
@IBDesignable
class CustomParentNavigationBarView: UIView {
override func awakeFromNib() {
super.awakeFromNib()
self.setHeight()
}
func setHeight() {
let deviceHasTopNotch = checkHasTopNotchOrNot()
var heightConstraint = NSLayoutConstraint()
if deviceHasTopNotch {
heightConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 88)
} else {
heightConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 64)
}
heightConstraint.isActive = true
self.addConstraint(heightConstraint)
}
func checkHasTopNotchOrNot() -> Bool {
if #available(iOS 11.0, tvOS 11.0, *) {
// with notch: 44.0 on iPhone X, XS, XS Max, XR.
// without notch: 20.0 on iPhone 8 on iOS 12+.
return UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0 > 20
}
return false
}
}
结果应该是这样的(红色视图),红色视图的高度应根据iPhone类型(88或64)而变化
对于初始值,我像这样在情节提要中设置视图的自动布局
答案 0 :(得分:2)
我可以看到两个问题。
您没有激活约束。添加此行
heightConstraint.isActive = true
您多次调用SetHeight。每次添加约束。这将导致约束冲突和不良行为。相反,只需创建一次约束并将其存储为成员。