nunzio giulio caggegi nunzio giulio caggegi - 3 months ago 8
Swift Question

Swift Button.setText doesn't work with gradient

I'm new in Swift and I have a problem. my button do not set the text if I try to use the gradient. here is my code:

let gradient:CAGradientLayer = CAGradientLayer()
let colorBottom = UIColor(red: 9/255.0, green: 137/255.0, blue: 133/255.0, alpha: 1.0).CGColor
let colorTop = UIColor(red: 222.0/255.0, green: 255.0/255.0, blue: 201.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 = 25.0


LoginButton.layer.addSublayer(gradient)
LoginButton.setTitle("Login", forState: UIControlState.Normal)
LoginButton.setTitleColor(UIColor.blackColor(), forState: .Normal)


self.view.addSubview(LoginButton)

Answer

Adding a sublayer works the same as adding a subview so adding the gradient layer may be covering the other layers where the text is drawn.

If you remove this line does it work?

LoginButton.layer.addSublayer(gradient)

If it does, try seeing how many layers are in LoginButton.layer.sublayers and try inserting the gradient layer behind one of those sublayers (wherever it looks the best) using one of the following methods:

-insertSublayer:above:
-insertSublayer:below:
-insertSublayer:atIndex:
Comments