Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting gradient both on Navigation Bar and Status bar

I'm trying to change the background of a navigation bar by creating a layer and adding it as a sublayer to the navigation bar. However, this is only affecting the navigation bar.

1

I wan't it to affect the whole top of the screen. Code included:

let navBarLayer = StyleUtils.createGradientLayerWithColors(color: StyleUtils.Colors.SKY_BLUE, frame: (self.navigationController?.navigationBar.bounds)!)

self.navigationController?.navigationBar.layer.addSublayer(navBarLayer)

The createGradientLayerWithColors function returns a CAGradientLayer for the given frame.

What am I missing? Thank you in advance.

EDIT:

I tried Nathaniel answer, but got this:

problem

It's worth mentioning that this is also a TableView.

SOLUTION:

I found this question that helped me solve the problem.

The final correct code is:

func setNavBarColor() {

    let navBar = self.navigationController?.navigationBar

    //Make navigation bar transparent
    navBar?.setBackgroundImage(UIImage(), for: .default)
    navBar?.shadowImage = UIImage()
    navBar?.isTranslucent = true

    //Create View behind navigation bar and add gradient
    let behindView = UIView(frame: CGRect(x: 0, y:0, width: UIApplication.shared.statusBarFrame.width, height: UIApplication.shared.statusBarFrame.height + (navBar?.frame.height)!))

    let layerTop = StyleUtils.createGradientLayerWithColors(color: StyleUtils.Colors.SKY_BLUE, frame: behindView.bounds)
    behindView.layer.insertSublayer(layerTop, at: 0)

    self.navigationController?.view.insertSubview(behindView, belowSubview: navBar!)

}
like image 418
PablodeAcero Avatar asked Dec 08 '16 19:12

PablodeAcero


Video Answer


1 Answers

This is how I manage it.

First I set the NavigationBar to transparent:

self.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.isTranslucent = true
self.navigationBar.backgroundColor = UIColor.clear

Then I add the gradient to the view behind the status bar and the navigation bar:

    let gradient = CAGradientLayer()
    gradient.frame = CGRect(x: 0, y: 0, width: UIApplication.sharedApplication().statusBarFrame.width, height: UIApplication.sharedApplication().statusBarFrame.height + self.navigationController!.navigationBar.frame.height)
    gradient.locations = [0.0,1.0]
    gradient.colors = [UIColor.anyColor().colorWithAlphaComponent(0.4).CGColor, UIColor.clearColor().CGColor]
    self.view.layer.addSublayer(gradient)
    self.view.backgroundColor = UIColor.clear
like image 150
Nathaniel Avatar answered Oct 13 '22 12:10

Nathaniel