Search code examples
swiftuinavigationcontrollerscreen-rotation

swift - frame issue in UINavigationController class when rotating


I've used a custom UINavigationController class to put a colour gradient across the navbar. The custom navclass determines the frame size of the navbar, then puts the gradient inside. Problem is, when I rotate from portrait to landscape, the gradient only fills the portrait portion of the landscape bar. I've only assigned the custom UINavigationController class to the navigation view in the storyboard.

So I'm guessing I somehow need to call a refresh for the frame size in the custom navclass when a rotation is done, but I'm not sure how or where?

Here's the relevant code snippet, from the override func viewDidLoad() of the custom navclass.

let gradientlayer = CAGradientLayer()
gradientLayer.frame = self.navigationBar.bounds
self.navigationBar.layer.inserSublayer(gradientLayer, atIndex: 1)

I tried putting it inside viewWillAppear(), but that didn't work. Any help?


Solution

  • viewDidLoad() and viewWillAppear() don't get called on rotation, so your code won't update the frame there.

    You should add gradientLayer.frame = self.navigationBar.bounds to viewWillLayoutSubviews() but leave the other code in viewDidLoad() so you don't wind up with multiple gradient layers.