gpt4 book ai didi

swift - 按钮渐变在 ios 12 (Swift 4.2) 后不起作用

转载 作者:行者123 更新时间:2023-11-28 14:12:44 27 4
gpt4 key购买 nike

随着 ios 12 和 swift 4.2 的到来,我的代码不再有效。它曾经是从左到右,深紫色到浅紫色的渐变按钮。我该如何解决这个问题?

// Gives the button gradient values
func setGradientButton(colorOne: UIColor, colorTwo: UIColor, x1: Double, y1: Double, x2: Double, y2: Double) {

let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradientLayer.locations = [0.0, 0.0]
gradientLayer.startPoint = CGPoint(x: x1, y: y1)
gradientLayer.endPoint = CGPoint(x: x2, y: y2)

layer.insertSublayer(gradientLayer, at: 0)
}


// Sets UI elements
func setUI(_ label : UILabel, _ button : UIButton) {

let colorOne = UIColor(red: 119.0 / 255.0, green: 85.0 / 255.0, blue: 254.0 / 255.0, alpha: 100.0)
let colorTwo = UIColor(red: 177.0 / 255.0, green: 166.0 / 255.0, blue: 251.0 / 255.0, alpha: 100.0)

button.setGradientButton(colorOne: colorOne, colorTwo: colorTwo, x1: 0.0, y1: 50, x2: 150, y2: 50)
button.layer.cornerRadius = 4
button.clipsToBounds = true
}

最佳答案

我无法假设您的代码之前为何有效,但我发现您的 CAGradientLayer 设置存在一些问题。

首先,locations 数组。根据Apple Documentation此值“定义每个梯度停止点的位置”。所以如果你想让你的渐变以一种颜色开始并以另一种颜色结束,你需要像那样设置你的locations

gradientLayer.locations = [0.0, 1.0]

另一个问题是startPointendPoint。同样,来自 documentation :

The point is defined in the unit coordinate space and is then mapped to the layer’s bounds rectangle when drawn.

因此您的点值应介于 0.01.0 之间。在单位坐标空间中,(0.0, 0.0) 是 View 的左上角,(1.0, 1.0) 是右下角。如果你想得到一个水平渐变,你需要像那样设置点

gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)

希望对你有帮助。

关于swift - 按钮渐变在 ios 12 (Swift 4.2) 后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52394332/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com