Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Adding gradient layer to button. Layer length error

let gradient: CAGradientLayer = CAGradientLayer()
let colorTop = UIColor(red: 112.0/255.0, green: 219.0/255.0, blue: 155.0/255.0, alpha: 1.0).CGColor
let colorBottom = UIColor(red: 86.0/255.0, green: 197.0/255.0, blue: 238.0/255.0, alpha: 1.0).CGColor

gradient.colors = [colorTop, colorBottom]
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
gradient.frame = loginButton.bounds
gradient.cornerRadius = 5
loginButton.layer.addSublayer(gradient)

Gradient too long

The resulting gradient runs off goes beyond the button's frame. Why does this happen?

like image 288
user2946632 Avatar asked Jun 16 '16 03:06

user2946632


2 Answers

Probably you are setting gradient layer in viewDidLoad() or viewWillAppear(). At that time controller did not calculated views sizes. At time you add this sublayer button size was not calculated yet, so sublayer size is wrong. So you should fix next things:

  1. First of all you should add gradient at viewDidAppear(), at this point all view's sizes are calculated.
  2. Second, you should use layer.insertSublayer(layer, atIndex:index) instead of addSublayer(layer). Because in your case sublayer will hide buttons native layer (title, background...)
  3. You should recalculate your sublayer size in viewDidLayoutSubviews(). Because when your button will change it's size (while rotating for example), sublayer will not change it's frame, so you should change it by yourself.
like image 53
Eugene Svaro Avatar answered Sep 27 '22 21:09

Eugene Svaro


Add clipsToBounds and cornerRadius to loginbutton. That should fix the problem.

loginButton.clipsToBounds = true
loginButton.layer.cornerRadius = 5;
like image 41
Nabin Singh Avatar answered Sep 27 '22 21:09

Nabin Singh