Reputation: 14123
My question is not regarding how to set gradient for UIButton
, but where to set it. This is how I am setting it :
let btnGradient = CAGradientLayer()
btnGradient.frame = button_start_course.bounds
btnGradient.colors = [(UIColor(red: 174.0 / 255.0, green: 127.0 / 255.0, blue: 183.0 / 255.0, alpha: 1.0).CGColor as CGColorRef), (UIColor(red: 78.0 / 255.0, green: 57.0 / 255.0, blue: 96.0 / 255.0, alpha: 1.0).CGColor as CGColorRef)]
button_start_course.layer.insertSublayer(btnGradient, atIndex: 0)
When I call this in viewDidLoad
, button_start_course gives incorrect bounds. To fix this, I called this code in viewDidAppear
. It works fine except for, the colour originally set for button_start_course on storyboard
appears first and then it changes to the gradient color.
How to fix this ?
Upvotes: 2
Views: 391
Reputation: 688
Add the code in viewDidLayoutSubviews
. To call it once, declare a boolean that set to true when the view did finish laying out subview.
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if !viewDidLayoutSubviews {
viewDidLayoutSubviews = true
// Code here
}
}
Upvotes: 2
Reputation: 801
You could set the gradient inside -(void)viewDidLayoutSubviews
Upvotes: 2
Reputation: 1080
set the gradient inside the viewWillAppear
instead of viewDidAppear
Upvotes: 0