Reputation: 13803
I need to make an IBDesignable to make a custom navigation bar file that will adjust the height of the view based on the iPhone type. if the iPhone has top notch like iPhone X,XR, then the height contraint will be 88, otherwise for iPhone 8 that does not has top notch, the height will be 64.
I need to set the height contraint, not the layer height. here is the code I use but it fails to update the height contraint
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
}
}
the result should be something like this (red view), the height of the red view should change according to iPhone type, either 88 or 64
for the initial value, I set the autolayout of the view in storyboard like this
Upvotes: 0
Views: 451
Reputation: 904
There are two problems that I can see.
You are not activating the constraints. Add this line
heightConstraint.isActive = true
You are calling SetHeight multiple times. Each time, a constraint is added. This will lead to constraint conflicts and poor behavior. Instead, just create the constraint once and store it as a member.
Upvotes: 2