Reputation: 3
I have created two custom classes : CutomView Class (subclass of UIView) and CustomButton Class(subclass of UIButton).
class CustomView: UIView {
override func drawRect(rect: CGRect) {
// Drawing code
layer.masksToBounds = true
layer.borderWidth = 2.0
layer.borderColor = UIColor(colorLiteralRed: 0.0/255, green: 64.0/255, blue: 128.0/255, alpha: 1).CGColor
layer.cornerRadius = 10.0
let startColor = UIColor(colorLiteralRed: 255.0/255, green: 204.0/255, blue: 1.0, alpha: 1.0).CGColor
let endColor = UIColor(colorLiteralRed: 0, green: 128.0/255, blue: 1.0, alpha: 1.0).CGColor
let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(origin: layer.frame.origin, size: layer.frame.size)
gradientLayer.colors = [startColor, endColor];
layer.addSublayer(gradientLayer)
}
and
@IBDesignable
class CustomButton: UIButton {
override func drawRect(rect: CGRect) {
// Drawing code
layer.masksToBounds = true
layer.borderWidth = 2.0
layer.borderColor = UIColor(colorLiteralRed: 0.0/255, green: 64.0/255, blue: 128.0/255, alpha: 1).CGColor
layer.cornerRadius = 2.0
let startColor = UIColor(colorLiteralRed: 192.0/255, green: 192.0/255, blue: 192.0/255, alpha: 1.0).CGColor
let endColor = UIColor(colorLiteralRed: 239.0/255, green: 239.0/255, blue: 239.0/255, alpha: 1.0).CGColor
let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(origin: layer.frame.origin, size: layer.frame.size)
gradientLayer.colors = [startColor, endColor];
layer.addSublayer(gradientLayer)
}
}
I used those custom subclasses to design the view and buttons. When I view the applied custom class they are working fine but for some reasons the button is not visible in simulator or the iOS Device.
It will be great if somebody could point me to the bug or help me fix it.
Storyboard and Preview shows the purple blue background and button
Simulator only displays purple blue background
Upvotes: 0
Views: 83
Reputation: 639
Your layer.addSublayer
call appends the layer to your hierarchy of layers. Thus, the gradient is the last thing drawn, effectively painting over your custom button. You want your gradient to be the background, so make sure it's the first layer drawn. Change
layer.addSublayer(gradientLayer)
to
layer.insertSublayer(gradientLayer, atIndex: 0)
Upvotes: 0