UINavigationBar gets cropped in landscape

2019-09-06 17:29发布

问题:

I am facing this situation where the navigation bar looks OK in portrait mode but gets cropped in landscape:

portrait

landscape

I subclassed UINavigationBar as follows:

class CustomNavigationBar: UINavigationBar {
    override func sizeThatFits(size: CGSize) -> CGSize {
        let newSize :CGSize = CGSize(width: self.frame.size.width, height: 64)
        return newSize
    }
}

and assigned it to the appropriate Navigation Controller via the StoryBoard:

but it makes no difference.

Any ideas?

回答1:

Navigation bar has different height in Portrait and Landscape mode. You should handle content of custom title view according to navigation bar height. Use autolayout to auto adjust the subview when navigation bar's height changes.



回答2:

I solved it by overriding sizeThatFits func in an extension. The idea is that it resets the size back to 44 which is the default for portrait:

// prevent navigation bars from resizing in landscape
extension UINavigationBar {
    public override func sizeThatFits(size: CGSize) -> CGSize {
        let portraitSize = CGSizeMake(UIScreen.mainScreen().bounds.width, 44)
        return portraitSize
    }
}