如何在UIButton背景中设置两种颜色 [英] How to set two colors in UIButton background

查看:386
本文介绍了如何在UIButton背景中设置两种颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在UIButton背景中设置两种不同的颜色.我知道如何设置一种颜色或边框等.但是我不知道如何在背景中设置两种不同的颜色.我展示了这个例子.我使用Swift 2

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

推荐答案

您可以使用具有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)

这篇关于如何在UIButton背景中设置两种颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆