Updated 12 January 2024
In this article you will learn about Add Gradient UIView using Extension in Swift.
A gradient view is a UIView that display a smooth transition of colours known as a gradient across its bounds, gradient’s are often used to enhance the visual appeal of user interfaces.
An extension add new functionality to an existing class. With help of extension you can add new functionality to an existing Swift class, structure, enumeration, or protocol without modifying its source code.
Extension provide a way to extend the behaviour of types, event those for which you do not have access to the original source code.
To create Gradient UiView using extension please follow bellow steps.
You may also check our Flutter App development services.
Before working on gradient UIView, we need to follow below steps.
First of all we need to create a new project where you will integrate gradient UIView.
After that we need to add a UIView either programatically or using Storyboard.
1 |
@IBOutlet var myUIView: UIView! |
The extension is a great concept in swift you can add your function is already predefined classes in swift 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) } } |
Above code is helpful to create gradient UIView.
We need to call extension UIView from viewDidLoad()
1 2 3 4 5 6 |
@objc override func viewDidLoad() { super.viewDidLoad() myUIView.backgroundColor = .white navigationItem.title = "Mobikul Blog" myUIView.applyGradient(colours: [UIColor.red , UIColor.yellow]) } |
Above code is helpful to call gradient UIView form viewDidLoad().
In this article we have discussed about Gradient View using Extension.
I hope this blog is helpful to understand Gradient.
For creating Gradient Color With Animation In Swift please visit here.
Thanks for reading this blog. You can also check other blogs from here for more knowledge.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.