Nitish Nitish - 1 year ago 121
iOS Question

UIButton gradient effect issue on viewDidLoad

My question is not regarding how to set gradient for

, 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
, button_start_course gives incorrect bounds. To fix this, I called this code in
. It works fine except for, the colour originally set for button_start_course on
appears first and then it changes to the gradient color.

How to fix this ?

Answer Source

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() {

   if !viewDidLayoutSubviews {
      viewDidLayoutSubviews = true
      // Code here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download