Search code examples
iosswiftuistoryboardnslayoutconstraintcagradientlayer

my view looks different on iphone 5 and iphone 6 even though it has constraints - what is wrong here?


In my swift app I am applying gradient to my view. I do it with the following code:

@IBOutlet weak var gradientView: UIView!

override func viewDidLoad(){
    super.viewDidLoad()

    let layer = CAGradientLayer()
    layer.frame = CGRect(x: 0, y: 0, width: self.gradientView.frame.width, height: self.gradientView.frame.height)
    layer.colors = [UIColor.clear.cgColor, UIColor.white.cgColor]
    gradientView.layer.addSublayer(layer)
}

in my storyboard the gradientView is the black one here:

enter image description here

its constraints are:

enter image description here

so it touches edges on each side, the top and the white panel on the bottom.

When I run it in iphone5 simulator I have:

enter image description here

and that's fine. But when I run it on iphone 6s, I see:

enter image description here

What's the problem here, since the constraints are applied?


Solution

  • The problem is that your gradientView's frame is not updated yet in viewDidLoad. Try this instead:

    let gradientLayer = CAGradientLayer() 
    
    override func viewDidLoad(){
        super.viewDidLoad()   
        gradientLayer.colors = [UIColor.clear.cgColor, UIColor.white.cgColor]
        gradientView.layer.addSublayer(gradientLayer)
    }
    
    override func viewDidLayoutSubviews(){
        super.viewDidLayoutSubviews()
        gradientLayer.frame = gradientView.bounds
    }