Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set two colors in UIButton background

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

enter image description here

like image 618
Alexander Khitev Avatar asked Dec 14 '22 10:12

Alexander Khitev


1 Answers

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)

enter image description here

like image 88
djromero Avatar answered Jan 11 '23 18:01

djromero