Gradient not covering full frame SWIFT

2019-08-23 16:38发布

问题:

I have the following extension to imageView:

extension UIImageView {
func addBlackGradientLayer(frame: CGRect){
    let gradient = CAGradientLayer()
    gradient.frame = frame
    gradient.colors = [UIColor.clear.cgColor, UIColor.black.cgColor]
    gradient.locations = [0.0, 1.0]
    self.layer.addSublayer(gradient)
}}

imageView.addBlackGradientLayer(frame: imageView.frame)

on applying this to the imageView, I am having the following output. I tried setting the constraints and also, the autolayout.

Following is the output after the execution:

回答1:

You need to call

imageView.addBlackGradientLayer(frame: imageView.bounds)

See: Cocoa: What's the difference between the frame and the bounds?