I have a project with a Tab Bar, and a custom Navigation bar for each of the tabs. Each of the Navigation bar UIViews have a height constraint constant set in the storyboard.
I would like to subclass this NSLayoutConstraint (for the Nav height), so that it changes the height for iPhone X. The Navigation bar needs to be much taller on an iPhone X, and since I'm not using "out of the box" objects, my constraints need to be manually set.
Essentially, I want to do something like the following in the subclass, so I don't have to repeat a bunch of code and make unnecessary outlets:
override func viewWillLayoutSubviews() {
navBarHeightConstraint.constant = navBarHeightConstraintConstant()
}
func navBarHeightConstraintConstant() -> CGFloat {
switch(UIScreen.main.bounds.height) {
case 812: // iPhone X
return 90
default: // all others
return 64
}
}
I have created the subclass, but don't know what methods to use to perform the above code.
class NavHeightFixiPhoneXConstraint: NSLayoutConstraint {
// Nothing... yet!
}
How can I subclass NSLayoutConstraint so that it displays a specific value for just iPhone X?
You can override the constant variable:
class NavHeightFixiPhoneXConstraint: NSLayoutConstraint {
override var constant: CGFloat {
set {
super.constant = newValue
}
get {
return navBarHeightConstant()
}
}
fileprivate func navBarHeightConstant() {
switch (UIScreen.main.bounds.height) {
case 812:
return 90
default:
return 64
}
layoutIfNeeded()
}
}
来源:https://stackoverflow.com/questions/46837977/subclassing-nslayoutconstraint-constant-based-on-screen-height