1

The problem is the navigation bar's image sits below the status bar.

Navigation bar sits below status bar

I had this previously working by adding a subview to the navigation bar but it seems stupid to do that when I only want an image.

I subclassed UINavigationController to deliver this behaviour for me. From reading the docs, the UIBarPositioning.TopAttached enum should allow this. The code is below.

import UIKit

class NavigationViewController: UINavigationController, UINavigationBarDelegate {

    let gradientLayer = CAGradientLayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationBar.delegate = self
        navigationBar.translucent = false

        gradientLayer.frame = CGRect(x: 0.0, y: 0.0,
                                     width: navigationBar.bounds.width,
                                     height: navigationBar.bounds.height)

        gradientLayer.applyGradient(colours: [UIColor(named: .primaryBrand), UIColor(named: .secondaryBrand)])

        navigationBar.setBackgroundImage(gradientLayer.renderAsImage(),
                                         forBarPosition: .TopAttached,
                                         barMetrics: .Default)
    }

    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }

    func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
        return .TopAttached
    }
}

Thanks for the help.

Amit Srivastava
  • 1,105
  • 9
  • 18
Ste Prescott
  • 1,789
  • 2
  • 22
  • 43

0 Answers0