1

After adding gradient layer in navigation bar, I don't see any right/left bar button items when i run on iOS 11. But the same code displays well on iOS 10/9..

Can anyone provide your valuable suggestions to fix this

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    setUpGradientNavigationBar()
}

func setUpGradientNavigationBar() {

    let lightRedColor = UIColor(red: CGFloat(197/255.0), green: 47/255.0, blue: 40/255.0, alpha: 1.0).cgColor
    let mediumRedColor = UIColor(red: CGFloat(176/255.0), green: 42/255.0, blue: 36/255.0, alpha: 1.0).cgColor
    let darkRedColor = UIColor(red: CGFloat(106/255.0), green: 25/255.0, blue: 22/255.0, alpha: 1.0).cgColor
    let colors = NSArray(objects: lightRedColor, mediumRedColor, darkRedColor)

    let gradientLayer = getGradientLayerForColors(colors, location: 0.5, andFrame: self.navigationController?.navigationBar.bounds)

    self.navigationController?.navigationBar.barTintColor =  UIColor.black
    self.navigationController?.navigationBar.layer.insertSublayer(gradientLayer, at: 1)
    self.navigationController?.navigationBar.tintColor = UIColor.white

    self.navigationController?.navigationBar.topItem?.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: nil, action: nil)

}

func getGradientLayerForColors(_ colors: NSArray, location:CGFloat, andFrame frame:CGRect?) -> CAGradientLayer {
    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = colors as [AnyObject]
    gradientLayer.locations = [0.0,NSNumber.init(value: Float(location))]
    gradientLayer.frame = frame!
    return gradientLayer
}

enter image description here

Mahi
  • 181
  • 1
  • 7

1 Answers1

0

Swift 5

  • Includes status bar in gradient.
  • Doesn't use an image.
  • Uses transparency so content is visible through nav bar.
extension UINavigationBar {

    func addGradient(_ toAlpha: CGFloat, _ color: UIColor) {
        let gradient = CAGradientLayer()
        gradient.colors = [
            color.withAlphaComponent(toAlpha).cgColor,
            color.withAlphaComponent(toAlpha).cgColor,
            color.withAlphaComponent(0).cgColor
        ]
        gradient.locations = [0, 0.8, 1]
        var frame = bounds
        frame.size.height += UIApplication.shared.statusBarFrame.size.height
        frame.origin.y -= UIApplication.shared.statusBarFrame.size.height
        gradient.frame = frame
        layer.insertSublayer(gradient, at: 1)
    }

}
Jimmy_m
  • 1,568
  • 20
  • 24