This question already has an answer here:
used below code for adding gradient layer for a view. After adding gradient layer to a view if i tried to add new subviews inside my gradient view the new view are not getting displayed
func setGradientBackground(_ view: UIView ,colorStart:CGColor ,colorEnd:CGColor,cornerRadius:CGFloat) {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorStart, colorEnd]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5);
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5);
gradientLayer.frame = view.bounds
gradientLayer.cornerRadius = cornerRadius
view.layer.addSublayer(gradientLayer)
}
if i extend a class with UIView how can i set gradient color directly from storyboard attributes inspector. I have seen this in some libraries (cosmos) where we can directly set rating color
Instead of adding gradient layer, create subclass of uiview and override layer property with gradientLayer
Gradient View:
Use:
It looks like you are using the layer directly and adding it to the view's backing layer. I recommend a simple UIView subclass that encapsulates the gradient behavior. The implementation is quite simple and the the largest benefit is the control you get over where it is rendered in the z dimension. Then you can just use the gradient view as a parent view for your content or if that isn't reasonable in your specific scenario, you could just insert the gradient view as a subview at index 0 using the
UIView.insert(_:,at:)
method of UIView instances. This would make your gradient view appear below the other views you add later.I recently began using gradients in one of my apps. Here is the code I used to define my custom gradient type.