简体   繁体   English

渐变颜色作为Swift4中UIButton的背景颜色

[英]Gradient color as a Background color of UIButton in Swift4

I have a button and i'm trying to set its background color gradient.I have three hex values which i converted to RGB and written three values in my code and pass all the three values to the button frame. 我有一个按钮,我正在尝试设置其背景颜色渐变。我有三个十六进制值,我转换为RGB并在我的代码中写入三个值,并将所有三个值传递给按钮框架。 But when i run the app button background not changes according to the color i have set in the code. 但是,当我运行应用程序按钮时,背景不会根据我在代码中设置的颜色而改变。 My code to get three color codes is this, 获取三种颜色代码的代码是这样的,

 let gradientColor = CAGradientLayer()
    gradientColor.frame = loginButton.frame
    let color1 = UIColor(red: 183, green: 46, blue: 79, alpha: 1)
    let color2 = UIColor(red: 232, green: 79, blue: 80, alpha: 1)
    let color3 = UIColor(red: 145, green: 21, blue: 79, alpha: 1)
    gradientColor.colors = [color1,color2,color3]
    self.loginButton.layer.addSublayer(gradientColor)

Try this and see: 试试看,看看:

@IBOutlet weak var loginButton: UIButton!
func testGradientButton() -> Void {
    let gradientColor = CAGradientLayer()
    gradientColor.frame = loginButton.frame
    gradientColor.colors = [UIColor.blue.cgColor,UIColor.red.withAlphaComponent(1).cgColor]
    self.loginButton.layer.insertSublayer(gradientColor, at: 0)
}

Here is result: 结果如下:

在此输入图像描述

Also note: Values for RGB colors in your code, are much higher than its normal value. 另请注意:代码中RGB颜色的值远高于其正常值。 See your console log, it might printed following error: 请参阅您的控制台日志,它可能会在出现以下错

[Graphics] UIColor created with component values far outside the expected range. [Graphics]使用远远超出预期范围的组件值创建的UIColor。 Set a breakpoint on UIColorBreakForOutOfRangeColorComponents to debug. 在UIColorBreakForOutOfRangeColorComponents上设置断点以进行调试。 This message will only be logged once. 此消息仅记录一次。

Divide all values with 255.0 and use insertSubLayer function. 将所有值除以255.0并使用insertSubLayer函数。

let color1 = UIColor(red: 183.0/255.0, green: 46.0/255.0, blue: 79.0/255.0, alpha: 1)
let color2 = UIColor(red: 232.0/255.0, green: 79.0/255.0, blue: 80.0/255.0, alpha: 1)
let color3 = UIColor(red: 145.0/255.0, green: 21.0/255.0, blue: 79.0/255.0, alpha: 1)

Here is result with your color code values: 以下是您的颜色代码值的结果:

func testGradientButton() -> Void {
    let gradientColor = CAGradientLayer()
    gradientColor.frame = loginButton.frame
    let color1 = UIColor(red: 183.0/255.0, green: 46.0/255.0, blue: 79.0/255.0, alpha: 1)
    let color2 = UIColor(red: 232.0/255.0, green: 79.0/255.0, blue: 80.0/255.0, alpha: 1)
    let color3 = UIColor(red: 145.0/255.0, green: 21.0/255.0, blue: 79.0/255.0, alpha: 1)
    gradientColor.colors = [color1.cgColor,color2.cgColor,color3.cgColor]
    self.loginButton.layer.insertSublayer(gradientColor, at: 0)
}

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM