Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclassing NSLayoutConstraint constant based on screen height

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?

like image 922
Joe Avatar asked Dec 13 '22 20:12

Joe


1 Answers

You can override the constant variable:

final class NavHeightFixiPhoneXConstraint: NSLayoutConstraint {

    override var constant: CGFloat {
        set {
            super.constant = newValue
        }
        get {
           return navBarHeightConstant()
        }
    }

    private func navBarHeightConstant() -> CGFloat {
        switch (UIScreen.main.bounds.height) {
         case 812:
            return 90
         default: 
             return 64
        }
    }
}
like image 153
Francesco Deliro Avatar answered May 07 '23 17:05

Francesco Deliro