How to create a custom navigation bar with gradient color in swift
- Create a new Cocoa Touch class call NavViewController.swift
class NavViewController: UIViewController {}
extension NavViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
- Create a new Single View Application and make ViewController.swift conform to UINavigationController
class ViewController: UINavigationController {}
- In the viewDidLoad() of ViewController push NavViewController() as viewController
override func viewDidLoad() {
self.pushViewController(NavViewController(), animated: false)
}
- In my case I want to use hexString colors, so that I have to create an extension of UIColor class for that. If you don't want, you can skip this step and move on.
extension UIColor {
convenience init(hexString: String, alpha: CGFloat = 1.0) {
let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let scanner = Scanner(string: hexString)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color: UInt32 = 0
scanner.scanHexInt32(&color)
let mask = 0x000000FF
let r = Int(color >> 16) & mask
let g = Int(color >> 8) & mask
let b = Int(color) & mask
let red = CGFloat(r) / 255.0
let green = CGFloat(g) / 255.0
let blue = CGFloat(b) / 255.0
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
func toHexString() -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return String(format:"#%06x", rgb)
}
}
- In the viewDidLoad() of the NavViewController class setup gradient of type CAGradientLayer(). Add this block of code to the bottom of the viewDidLoad()
// setup gradient for the navigation bar
let header_gradient = CAGradientLayer()
header_gradient.frame = (navigationController?.navigationBar.bounds)!
header_gradient.color = [UIColor(hexString: "#FF825C"), UIColor(hexString: "#FFB84C")]
header_gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
header_gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
- After that, Render the gradient we just create to UIImage. Add this block of code the bottom of viewDidLoad()
// render the gradient to UIImage
UIGraphicsBeginImageContext(header_gradient.bounds.size)
header_gradient.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
- Now we can set the background image of the navigation bar with the image we just render with gradient color
self.navigationController?.navigationBar.setBackgroundImage(image, for: .default)
That's all for this. Now go ahead and run the application. You will get a beautiful custom navigation bar with gradient color.