There may be a situation when we want to add gradient to UIView. As we know every UIView is backed by a layer. We can also add or insert as many layers to UIView with different functionality. As we can add gradient color to UIView, add animation layer and many more .
It is very easy to add a layer to UIView as:
It is very easy to add a layer to UIView as:
let topgradientLayer = CAGradientLayer()
topGredientLayer.frame = yourFrame.bounds
topGredientLayer.startPoint = CGPointMake(0.5, 1.0)
topGredientLayer.endPoint = CGPointMake(0.5, 0.0)
topGredientLayer.colors = [UIColor(colorLiteralRed: 1.0, green: 1.0, blue: 1.0, alpha: 0.0).CGColor, UIColor(colorLiteralRed: 1.0, green: 1.0, blue: 1.0, alpha: 1.0).CGColor]
yourFrame.layer.insertSublayer(topGredientLayer, atIndex: 0)
This way we can add a layer to UIVIew.The default layer of UIView resize with its view but sublayer does not resize with its view .
To make this work we create a subclass of UIView and write above code in awakeFromNib() method . And also override layoutSublayersOfLayer().
For example:
override func awakeFromNib() {
//add your layer here
}
override func layoutSublayersOfLayer(layer: CALayer) {
yourSubLayer.frame = self.bounds
}
No comments:
Post a Comment