将渐变应用于按钮不会迅速反映
Posted
技术标签:
【中文标题】将渐变应用于按钮不会迅速反映【英文标题】:Applying Gradient to button doesn't reflect in swift 【发布时间】:2019-07-30 10:38:10 【问题描述】:我写了以下代码,不知道我做错了什么按钮没有反映渐变
我也尝试在 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)
我想将渐变垂直应用到我的按钮。
【问题讨论】:
【参考方案1】:很简单,给你
@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
【讨论】:
我在自定义类 func applyGradient(colors : [Any]) gradient.frame = self.bounds gradient.colors = colors gradient.startPoint = CGPoint.zero gradient.endPoint = CGPoint. init(x: 0.0, y: 0.9) gradient.locations = [0,1] self.layer.addSublayer(gradient) self.layer.cornerRadius = self.frame.height / 2 self.clipsToBounds = true以上是关于将渐变应用于按钮不会迅速反映的主要内容,如果未能解决你的问题,请参考以下文章