【发布时间】:2020-08-27 05:51:21
【问题描述】:
我在UIView 的扩展中定义了这个函数,我用它在UIView 上设置渐变背景:
func setGradientBackground(colorTop: UIColor, colorBottom: UIColor, withCornerRadius : CGFloat){
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorBottom.cgColor, colorTop.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
gradientLayer.locations = [0, 1]
gradientLayer.frame = bounds
gradientLayer.cornerRadius = withCornerRadius
layer.insertSublayer(gradientLayer, at: 0)
}
用法如下:
view.setGradientBackground(colorTop: UIColor.blue, colorBottom: UIColor.red, withCornerRadius: 10)
问题是,如果我已经在一个视图上调用了这个函数一次,那么我第二次调用它时,它什么也不做。我怀疑这是由先前插入的subLayer 引起的。
我已经尝试添加:
if layer.sublayers?.count ?? 0 > 0 {
layer.sublayers?.remove(at: 0)
}
到该函数的顶部,但这会导致代码崩溃并出现BAD_INSTRUCTION 异常。
【问题讨论】:
标签: ios swift extension-methods cagradientlayer