The following code creates a square UIView frame with a gradient layer inside a detail view controller. However, the square.layer.cornerRadius doesn't show. It remains square.
class Colors {
let colorTop = UIColor(red: 68.0/255.0, green: 107.0/255.0, blue: 207.0/255, alpha: 1.0).cgColor
let colorBottom = UIColor(red: 68.0/255.0, green: 108.0/255.0, blue: 179.0/255, alpha: 1.0).cgColor
let gl: CAGradientLayer
init() {
gl = CAGradientLayer()
gl.colors = [ colorTop, colorBottom]
gl.locations = [ 0.0, 1.0]
}
}
class DetailViewController: UIViewController {
func viewWillAppear {
let colors = Colors() // is a class that creates the gradient
let square = UIView(frame: CGRect(x: 18, y: 109, width: 60, height: 60))
square.layer.cornerRadius = 10
let backgroundLayer = colors.gl
backgroundLayer.frame = square.frame
backgroundLayer.maskToBounds = true
view.layer.insertSublayer(backgroundLayer, at: 1)
}
}
You are giving cornerRadius to your square view but not adding it your main view instead you are creating backgroundLayer and adding it your main view.
BackgroundLayer is not rounded as the when your are assigning the square view's frame a rectangular(square in your case) is assigned to the backgroundLayer without any cornerRadius.
You should add your backgroundLayer to your square view and then add the square view to your main view. Like,
square.layer.insertSublayer(backgroundLayer, at: 1)
view.addSubview(square)
Also do,
square.clipsToBounds = true
This should resolve your issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With