How to set two colors in UIButton background

怎甘沉沦 提交于 2019-12-06 00:08:36

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)

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!