Kex Kex - 4 months ago 52
iOS Question

Issues setting gradient image as UINavigationBar background

I'm trying to set a gradient image background for my navigation bar. Code is like so:

extension CAGradientLayer {

class func gradientLayerForBounds(bounds: CGRect, startColor: UIColor, endColor: UIColor) -> CAGradientLayer {
let layer = CAGradientLayer()
layer.frame = bounds
layer.colors = [startColor.CGColor, endColor.CGColor]
return layer
}
}


Then in my view controller:

func imageLayerForGradientBackground() -> UIImage{

var updatedFrame = self.navigationController!.navigationBar.bounds
updatedFrame.size.height += 20 //Status bar
let layer = CAGradientLayer.gradientLayerForBounds(updatedFrame, startColor: UIColor(hexString: "5FD238")!, endColor: UIColor(hexString: "A5E589")!)
UIGraphicsBeginImageContext(layer.bounds.size)
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image

}


viewDidLoad:

navigationController!.navigationBar.translucent = false
navigationController!.navigationBar.tintColor = UIColor.whiteColor()
navigationController!.navigationBar.setBackgroundImage(imageLayerForGradientBackground(), forBarMetrics: UIBarMetrics.Default)


The issue is that all my views under the navigation bar are now pushed down by what look like the height of the navigation bar (as drawn badly in the diagram below):

enter image description here

Why is this happening? Any pointers on this would be greatly appreciated! Thanks!

EDIT:

func setupDrawerView() {

answerDrawerView = AnswerDrawerView(frame: CGRect(x: 0, y: UIScreen.mainScreen().bounds.size.height - AnswerDrawerView.submitTabHeight, width: UIScreen.mainScreen().bounds.size.width, height: UIScreen.mainScreen().bounds.height*0.75))
answerDrawerView.delegate = self
view.addSubview(answerDrawerView)
}

Answer

This has nothing whatever to do with the gradient. It's all about this line:

navigationController!.navigationBar.translucent = false

As soon as you say that, the main view stops underlapping the navigation bar. Well, you've positioned your views absolutely instead of using auto layout, so since the Biology button was, let's say, 35 points down from the top of the main view, it is still 35 points down from the top of the main view — but the top of the main view is now at the bottom of the navigation bar. Hence the gap.

The moral: use auto layout! This kind of situation is exactly what it is for. Position your views in relation to the top layout guide, not the top of the main view, and all will be well.