I want to set two different colors in UIButton
background. I know how to set one color or border and etc. But I don't know how to set two different colors in the background. I show the example. I use Swift 2
You can use a gradient with 2 pair of repeating colours:
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = button.bounds
gradient.colors = [
UIColor.greenColor().CGColor,
UIColor.greenColor().CGColor,
UIColor.blackColor().CGColor,
UIColor.blackColor().CGColor
]
/* repeat the central location to have solid colors */
gradient.locations = [0, 0.5, 0.5, 1.0]
/* make it horizontal */
gradient.startPoint = CGPointMake(0, 0.5)
gradient.endPoint = CGPointMake(1, 0.5)
button.layer.insertSublayer(gradient, atIndex: 0)
You can change the orientation playing with the start/end points:
gradient.startPoint = CGPointMake(0, 0)
gradient.endPoint = CGPointMake(1, 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With