gpt4 book ai didi

ios - 将渐变应用于按钮不会 swift 反射(reflect)

转载 作者:行者123 更新时间:2023-11-29 05:33:39 26 4
gpt4 key购买 nike

我编写了以下代码,但不知道我做错了什么按钮没有反射(reflect)渐变

我还尝试在 awakefromNib 下调用我的函数

class ButtonGradient: UIButton {

var color1 = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
var color2 = #colorLiteral(red: 0.521568656, green: 0.1098039225, blue: 0.05098039284, alpha: 1)

var gradient = CAGradientLayer()

override init(frame: CGRect) {
super.init(frame: frame)
applyGradient()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
applyGradient()

}


func applyGradient() {

gradient.frame = self.bounds
gradient.colors = [color1,color2]
gradient.startPoint = CGPoint.zero
gradient.endPoint = CGPoint.init(x: 0.0, y: 0.5)
gradient.locations = [0,1]
self.layer.addSublayer(gradient)


}
}

我想将渐变垂直应用到我的按钮。

最佳答案

很简单,给你

    @IBDesignable class GradientButton: UIButton {

@IBInspectable var topColor: UIColor = .white
@IBInspectable var bottomColor: UIColor = .black

override class var layerClass: AnyClass {
return CAGradientLayer.self
}

override func layoutSubviews() {
(layer as? CAGradientLayer)?.colors = [topColor.cgColor, bottomColor.cgColor]
}

}

只需将类从 UIButton 更改为 GradientButton

关于ios - 将渐变应用于按钮不会 swift 反射(reflect),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57269757/

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