I'm trying to generate a view with a gradient color background (A solid color to transparent) at runtime. Is there a way of doing that?
相关问题
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- “Zero out” sensitive String data in Swift
- Get the NSRange for the visible text after scroll
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- Swift - hide pickerView after value selected
- How do you detect key up / key down events from a
- didBeginContact:(SKPhysicsContact *)contact not in
- Attempt to present UIAlertController on View Contr
SWIFT 3
To add a gradient layer on your view
Bind your view outlet
Define the CAGradientLayer()
Here is the code you have to write in your viewDidLoad
YOURVIEW.layoutIfNeeded()
gradient.startPoint = CGPoint(x: CGFloat(0), y: CGFloat(1)) gradient.endPoint = CGPoint(x: CGFloat(1), y: CGFloat(0)) gradient.frame = YOURVIEW.bounds gradient.colors = [UIColor.red.cgColor, UIColor.green.cgColor] gradient.colors = [ UIColor(red: 255.0/255.0, green: 56.0/255.0, blue: 224.0/255.0, alpha: 1.0).cgColor,UIColor(red: 86.0/255.0, green: 13.0/255.0, blue: 232.0/255.0, alpha: 1.0).cgColor,UIColor(red: 16.0/255.0, green: 173.0/255.0, blue: 245.0/255.0, alpha: 1.0).cgColor] gradient.locations = [0.0 ,0.6 ,1.0] YOURVIEW.layer.insertSublayer(gradient, at: 0)
To give gradient color to UIView (swift 4.2)
How to use
Objective-C:
Swift:
Info: use startPoint and endPoint to change direction of gradient.
If there are any other views added onto this
UIView
(such as aUILabel
), you may want to consider setting the background color of thoseUIView
’s to[UIColor clearColor]
so the gradient view is presented instead of the background color for sub views. UsingclearColor
has a slight performance hit.I've extended the accepted answer a little using Swift's extension functionality as well as an enum.
Oh and if you are using Storyboard like I do, make sure to call
gradientBackground(from:to:direction:)
inviewDidLayoutSubviews()
or later.Swift 3
Its a good idea to call the solutions above to update layer on the
to get the views updated correctly
I have implemented this in swift with an extension:
Swift 3
Swift 2.2
No I can set a gradient on every view like this: