I've got this function defined in an extension of UIView
which I use to set the gradient background on a 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)
}
It is used as follows:
view.setGradientBackground(colorTop: UIColor.blue, colorBottom: UIColor.red, withCornerRadius: 10)
The problem is, if I have already called this function once on a view, the second time I call it, it does not do anything. I suspect this is caused by the subLayer
persisting from the previous insertion.
I've tried adding:
if layer.sublayers?.count ?? 0 > 0 {
layer.sublayers?.remove(at: 0)
}
to the top of that function, but that causes by code to crash with a BAD_INSTRUCTION
exception.
You can get the Gradient layer and can remove from view anywhere you want to... Not just by adding it again you remove it..
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")
}
The easiest option would be to check to see if the layer's sublayer is a gradient layer. This isn't perfectly safe because if you happen to have another gradient layer at index 0 of the sublayers, it will change the incorrect sublayer.
func setGradientBackground(colorTop: UIColor, colorBottom: UIColor, withCornerRadius cornerRadius: CGFloat) {
let gradientLayer = layer.sublayers?.first as? CAGradientLayer ?? CAGradientLayer()
// The rest of your existing layer customization code here
guard gradientLayer.superlayer != self else {
return
}
layer.sublayers?.insertSublayer(gradientLayer, at: 0)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.