【发布时间】:2018-10-16 02:29:10
【问题描述】:
我需要制作一个 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
对于初始值,我像这样在故事板中设置视图的自动布局
【问题讨论】:
-
translatesAutoresizingMaskIntoConstraints = false? -
我没有那个代码
-
尝试添加。
-
我必须把 translatesAutoresizingMaskIntoConstraints = false 放在哪里?在 awakefromNib 中?
-
如果您使用 storboard,它应该可以作为一个选项使用。
标签: ios swift uiview autolayout