gpt4 book ai didi

ios - CAGradientLayer 不显示

转载 作者:行者123 更新时间:2023-11-28 05:49:33 31 4
gpt4 key购买 nike

我已经查看了很多其他类似问题的答案,但似乎没有一个答案能解决我的问题,因此寻求一点帮助。

我正在尝试对 UIButton 应用垂直渐变,但渐变层没有显示在我的 View 中。相关代码如下:

let darkPurple = UIColor(displayP3Red: 61.0/255.0, green: 3.0/255.0, blue: 110.0/255.0, alpha: 1.0)
let lightPurple = UIColor(displayP3Red: 90.0/255.0, green: 32.0/255.0, blue: 130.0/255.0, alpha: 1.0)

let addButton = UIButton(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
addButton.title = "Start counting"
addButton.layer.cornerRadius = 30.0
addButton.layer.borderWidth = 1.0
addButton.layer.borderColor = darkPurple.cgColor
addButton.translatesAutoresizingMaskIntoConstraints = false
myView.addSubview(addButton)
addButton.applyGradient(with: [lightPurple, darkPurple], gradientOrientation: .vertical)

...以及应用渐变的代码:

typealias GradientPoints = (startPoint: CGPoint, endPoint: CGPoint)

enum GradientOrientation {
case topRightBottomLeft
case topLeftBottomRight
case horizontal
case vertical

var startPoint: CGPoint {
return points.startPoint
}

var endPoint: CGPoint {
return points.endPoint
}

var points: GradientPoints {
switch self {
case .topRightBottomLeft:
return (CGPoint(x: 0.0, y: 1.0), CGPoint(x: 1.0, y: 0.0))
case .topLeftBottomRight:
return (CGPoint(x: 0.0, y: 0.0), CGPoint(x: 1.0, y: 1.0))
case .horizontal:
return (CGPoint(x: 0.0, y: 0.0), CGPoint(x: 1.0, y: 0.0))
case .vertical:
return (CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.0, y: 1.0))
}
}
}

extension UIView {
func applyGradient(with colors: [UIColor], gradientOrientation orientation: GradientOrientation) {
let gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = colors.map { $0.cgColor }
gradient.startPoint = orientation.startPoint
gradient.endPoint = orientation.endPoint
gradient.borderColor = self.layer.borderColor
gradient.borderWidth = self.layer.borderWidth
gradient.cornerRadius = self.layer.cornerRadius
gradient.masksToBounds = true
gradient.isHidden = false

self.layer.insertSublayer(gradient, at: 0)
}
}

这是我得到的: empty button

感谢您的帮助!

最佳答案

对于已经花费数小时搜索的人(就像我一样):

请确保您的颜色数组包含 CGColor 而不是 UIColor,根据文档:

colors

An array of CGColorRef objects defining the color of eachgradient stop. Animatable.

https://developer.apple.com/documentation/quartzcore/cagradientlayer/1462403-colors

奖励:这个小代码片段会导致应用程序崩溃,如果您再次错过它(推荐使用#if DEBUG)

extension CAGradientLayer {
dynamic var colors: [Any]? {
get { self.value(forKey: "colors") as? [Any] }
set {
if let newValue = newValue {
for color in newValue {
if color is UIColor {
fatalError("CAGradientLayer.colors must contain only CGColor! UIColor was found")
}
}
}
super.setValue(newValue, forKey: "colors")
}
}
}

关于ios - CAGradientLayer 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53385203/

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