1

After applying gradient to the view the result is as shown on the picture. Gradient colour (yelow part) doesn't stretch to the view bounds. Both yellow and red is is the same view. Can't figure out what's going on. And here's my code:

let gradientLayer = CAGradientLayer()
        gradientLayer.frame = bounds
        //gradientLayer.frame = frame
        //gradientLayer.bounds = frame
        gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.startPoint = CGPoint(x: 1.0, y: 1.0)
        gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.0)

        layer.insertSublayer(gradientLayer, at: 0

colorOne and colorTwo are defined elsewhere.

enter image description here )

Anyone encounter the same problem?

background gradient

Peter O.
  • 32,158
  • 14
  • 82
  • 96
new_project
  • 281
  • 1
  • 3
  • 10
  • 1
    Your code is called before the parent view frame is updated (to the device size). That's why you have the issue. in viewDidLayoutSubViews, update the gradient frames. – Larme Jan 07 '20 at 16:09
  • https://stackoverflow.com/questions/47937307/why-gradient-layer-in-uitableviewcell-not-cover-entire-frame https://stackoverflow.com/questions/52348716/gradient-view-not-working-programmatically-with-swift https://stackoverflow.com/questions/28269452/subview-frame-is-incorrect-when-creating-uicollectionviewcell etc. – Larme Jan 07 '20 at 16:21

2 Answers2

0

This has to do with the constraints in your storyboard not being applied until the subviews are laid out. At viewDidLoad() the view has a fixed size from the storyboard. If you move the code that sets the layer's frame to viewDidLayoutSubviews() the constraints have been applied to yourView and it then has the correct frame. You can then set the layer's frame.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    gradientLayer.frame = yourView.bounds
}

Then it will fill the whole view.

Schaheer Saleem
  • 479
  • 1
  • 3
  • 12
0

I spoke too soon... now it doesn't update to bounds when changing orientation (it's showing both horizontal and vertical gradient at the same time) Any thoughts?

enter image description here

new_project
  • 281
  • 1
  • 3
  • 10