我已经在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
异常而崩溃。
我在这里找到了问题,将名称设置为您的CAGradientLayer
。这将帮助您删除该特定层。
通过以下代码更新您的方法:
func setGradientBackground(colorTop: UIColor, colorBottom: UIColor, withCornerRadius : CGFloat){
for layer in layer.sublayers ?? [] {
if layer.name == "GradientLayer" {
layer.removeFromSuperlayer()
}
}
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
gradientLayer.name = "GradientLayer"
layer.insertSublayer(gradientLayer, at: 0)
}
您可以获取Gradient图层,并可以从视图中任何想要的位置删除它...不仅可以通过再次添加它来删除它。
if let gradientLayer = (yourView.layer.sublayers?.compactMap { $0 as? CAGradientLayer })?.first {
print("gradientLayer is presnet")
gradientLayer.removeFromSuperlayer()
} else {
print("its not added on layer yet")
}