Add Gradient in Navigation Bar
The extension is a great concept in swift in swift you can add your function is already predefined classes in swift 3.0 like String, UIView, UIColor , UINavigation , UITabbar etc.A while creating an extension you can write it anywhere in your project.To create a gradient extension you have to create an extension of UINavigationBar class.The main benefit of extension is that it will reduce many of your code lines like you have to use the gradient 5 times in your project so you have to write the same code 5 times in your project while creating an extension you have to write it only once it will also save the application memory.Example to create an extension:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
extension UINavigationBar { /// Applies a background gradient with the given colors func applyNavigationGradient( colors : [UIColor]) { var frameAndStatusBar: CGRect = self.bounds frameAndStatusBar.size.height += 20 // add 20 to account for the status bar setBackgroundImage(UINavigationBar.gradient(size: frameAndStatusBar.size, colors: colors), for: .default) } /// Creates a gradient image with the given settings static func gradient(size : CGSize, colors : [UIColor]) -> UIImage? { // Turn the colors into CGColors let cgcolors = colors.map { $0.cgColor } // Begin the graphics context UIGraphicsBeginImageContextWithOptions(size, true, 0.0) // If no context was retrieved, then it failed guard let context = UIGraphicsGetCurrentContext() else { return nil } // From now on, the context gets ended if any return happens defer { UIGraphicsEndImageContext() } // Create the Coregraphics gradient var locations : [CGFloat] = [0.0, 1.0] guard let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: cgcolors as NSArray as CFArray, locations: &locations) else { return nil } // Draw the gradient context.drawLinearGradient(gradient, start: CGPoint(x: 0.0, y: 0.0), end: CGPoint(x: size.width, y: 0.0), options: []) // Generate the image (the defer takes care of closing the context) return UIGraphicsGetImageFromCurrentImageContext() } } |
how to use Extension:-
- Adding gradient to theUINavigationBar:-
1navigationController?.navigationBar.applyNavigationGradient(colors: [UIColor.red , UIColor.yellow])