To set the background color of UINavigation bar , we set the barTintColor property of UINavigationBar.
self.navigationController?.navigationBar.barTintColor = YOUR_COLOR
But what if you want to set the gradient color as tint color. For this we can take either create a CAGradientLayer with desired color and then render that layer in current graphics context and get the image from the current context and set backgroundImage of the UINavigationBar.
Second we can draw a gradient image using core graphics without creating a CAGradientLayer and then set the backgroundImage of UINavigationBar.
Here we are going with second one, using core graphics. Swift provide us many functionalities to write reusable code so that we can use it anywhere in our application.
extension UIColor {
convenience init(r: Float, g: Float, b: Float,alpha:Float) {
self.init(colorLiteralRed: r/255, green: g/255, blue: b/255, alpha: alpha)
}
}
extension UINavigationBar{
func gradeintBarTintColor(with gradient:[UIColor]){
var frameAndStatusBarSize = self.bounds
frameAndStatusBarSize.size.height += 20
setBackgroundImage(UINavigationBar.gradient(size: frameAndStatusBarSize.size, color: gradient), for: .default)
}
static func gradient(size:CGSize,color:[UIColor]) -> UIImage?{
//turn color into cgcolor
let colors = color.map{$0.cgColor}
//begin graphics context
UIGraphicsBeginImageContextWithOptions(size, true, 0.0)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
// From now on, the context gets ended if any return happens
defer {UIGraphicsEndImageContext()}
//create core graphics context
let locations:[CGFloat] = [0.0,1.0]
guard let gredient = CGGradient.init(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors as NSArray as CFArray, locations: locations) else {
return nil
}
//draw the gradient
context.drawLinearGradient(gredient, start: CGPoint(x:0.0,y:0.0), end: CGPoint(x:0.0,y:size.height), options: [])
// Generate the image (the defer takes care of closing the context)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
Usage:
Here I added gradient from top to bottom, you can change the implementation as per your requirements.
In your view controller, use like this:
//add gradeint color as bartint color
let colors = [UIColor(r: 73.0, g: 183.0, b: 229.0, alpha: 1.0),UIColor(r: 44.0, g: 154.0, b: 202.0, alpha: 1.0)]
self.navigationController?.navigationBar.gradeintBarTintColor(with: colors)
Results:
References: