Subclassing NSLayoutConstraint constant based on screen height

僤鯓⒐⒋嵵緔 提交于 2019-12-10 10:14:29

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!