自定义 UIButton 类 - 渐变离开按钮边框
Posted
技术标签:
【中文标题】自定义 UIButton 类 - 渐变离开按钮边框【英文标题】:custom UIButton class - gradient going out off button borders 【发布时间】:2021-11-07 13:41:39 【问题描述】:我正在做自定义 UIButton 类,我希望它具有渐变背景。我的渐变颜色看起来很完美,但它超出了按钮边框
我的代码:
class CustomButton: UIButton
override init(frame: CGRect)
super.init(frame: frame)
setup()
required public init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)
setup()
func setup()
layer.cornerRadius = 25.0
layer.borderWidth = 1
gradientLayer.frame = layer.bounds
addShadow()
private lazy var gradientLayer: CAGradientLayer =
let color1 = UIColor(red: 254.0/255.0, green: 79.0/255.0, blue: 50.0/255.0, alpha: 1.0).cgColor
let color2 = UIColor(red: 255.0/255.0, green: 26.0/255.0, blue: 107.0/255.0, alpha: 1.0).cgColor
let gradient = CAGradientLayer()
gradient.frame = layer.bounds
gradient.colors = [color1, color2]
gradient.startPoint = CGPoint(x: 0, y: 0.5)
gradient.endPoint = CGPoint(x: 1, y: 0.5)
gradient.locations = [0,1]
gradient.cornerRadius = 25
layer.insertSublayer(gradient, at: 0)
return gradient
()
func addShadow()
layer.shadowOpacity = 1
layer.shadowRadius = 1.0
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 1
layer.shadowOffset = CGSize(width: 0, height: 3)
它的外观如下:
【问题讨论】:
覆盖layoutSubview
方法并在其中设置框架
【参考方案1】:
从设置中删除 gradientLayer.frame
并添加 layoutSubviews
。
同时设置self.bounds
而不是layer.bounds
。
override func layoutSubviews()
super.layoutSubviews()
gradientLayer.frame = self.bounds // < Here
注意:从var gradientLayer
中删除gradient.frame = layer.bounds
。不需要。
【讨论】:
【参考方案2】:只需覆盖 layerClass
即可避免调整大小问题(使用约束自动调整大小)
class CustomButton: UIButton
override init(frame: CGRect)
super.init(frame: frame)
setup()
required public init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)
setup()
override class var layerClass: AnyClass
CAGradientLayer.self
var gradientLayer: CAGradientLayer
layer as! CAGradientLayer
func setup()
gradientLayer.cornerRadius = 25.0
gradientLayer.borderWidth = 1
let color1 = UIColor(red: 254.0/255.0, green: 79.0/255.0, blue: 50.0/255.0, alpha: 1.0).cgColor
let color2 = UIColor(red: 255.0/255.0, green: 26.0/255.0, blue: 107.0/255.0, alpha: 1.0).cgColor
gradientLayer.colors = [color1, color2]
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
gradientLayer.locations = [0,1]
gradientLayer.shadowOpacity = 1
gradientLayer.shadowRadius = 1.0
gradientLayer.shadowColor = UIColor.black.cgColor
gradientLayer.shadowOpacity = 1
gradientLayer.shadowOffset = CGSize(width: 0, height: 3)
【讨论】:
以上是关于自定义 UIButton 类 - 渐变离开按钮边框的主要内容,如果未能解决你的问题,请参考以下文章
iOS:自定义按钮(UIButton 的子类) - 无法更改边框属性