4

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

1
  • You probably need to use an image as background. I highly doubt there is a way to set multiple color side by side like this. Commented Oct 30, 2015 at 11:48

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

Comments

3

You can use CAGradientLayer to make it

let layer : CAGradientLayer = CAGradientLayer() layer.frame.size = button.frame.size layer.startPoint = CGPointZero layer.endPoint = CGPointMake(1, 0) let colorGreen = UIColor.greenColor().CGColor let colorBlack = UIColor.blackColor().CGColor layer.colors = [colorGreen, colorGreen, colorBlack, colorBlack] layer.locations = [0.0, 0.5, 0.5, 1.0] button.layer.insertSublayer(layer, atIndex: 0) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.