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 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 UIView 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 |
extension UIView { func applyGradient(colours: [UIColor]) -> Void { self.applyGradient(colours: colours, locations: nil) } func applyGradient(colours: [UIColor], locations: [NSNumber]?) -> Void { let gradient: CAGradientLayer = CAGradientLayer() gradient.frame = self.bounds gradient.colors = colours.map { $0.cgColor } gradient.locations = locations self.layer.addSublayer(gradient) } } |
how to use Extension:-
1 |
yourView.applyGradient(colours: [UIColor.red , UIColor.yellow]) |
1 |
button.applyGradient(colours: GlobalData.Credentials.gradientArray) |
Add Transparency To GRADIENT:-
If you want to add transparency to the gradient, then you have to change the alpha of your colors:-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
extension UIView { func applyGradient(colours: [UIColor]) -> Void { self.applyGradient(colours: colours, locations: nil) } func applyGradient(colours: [UIColor], locations: [NSNumber]?) -> Void { let gradient: CAGradientLayer = CAGradientLayer() gradient.frame = self.bounds gradient.colors = colours.map { $0.withAlphaComponent(0.90).cgColor } gradient.locations = locations self.layer.addSublayer(gradient) } } |
Be the first to comment.