IOS8: auto layout and gradient

Setup:

I have a View Controller , which consists of a View and a Container View .

enter image description here

View (orange) - from pinned to top 0, left 0 and right 0.

Container View (gray) - from pinned to bottom 0, left 0 and right 0.

View Bottom Space to: Container View = 0

View Proportional Height to Container View = 1

Desired results: I would like to add a gradient to the background of the View (orange)

I tried:

I use Auto-layout with class sizes to get different behavior on a different screen.

code:

 class ViewController: UIViewController { @IBOutlet weak var graphView: UIView! @IBOutlet weak var containerView: UIView! override func viewDidLoad() { super.viewDidLoad() let backgroundColor = CAGradientLayer().graphViewBackgroundColor() backgroundColor.frame = self.graphView.frame self.graphView.layer.addSublayer(backgroundColor) } 

I have a category:

 extension CAGradientLayer { func graphViewBackgroundColor() -> CAGradientLayer { let topColor = UIColor(red: (160/255.0), green: (160/255.0), blue: (160/255.0), alpha: 1) let bottomColor = UIColor(red: (52/255.0), green: (53/255.0), blue: (52/255.0), alpha: 1) let gradientColors: [CGColor] = [topColor.CGColor, bottomColor.CGColor] let gradientLocations: [Float] = [0.0, 1.0] let gradientLayer: CAGradientLayer = CAGradientLayer() gradientLayer.colors = gradientColors gradientLayer.locations = gradientLocations return gradientLayer } } 

Result:

enter image description here

As you can see, the gradient does not cover the entire View .

Question: How can I get a gradient to cover the whole View

Update:

When I put the code in viewDidLayoutSubviews() It looks weird when I rotate:

enter image description here

0
source share
2 answers

Just do it inside viewDidLayoutSubviews:

 override func viewDidLayoutSubview() { super.viewDidLayoutSubviews backgroundColor.frame = self.graphView.bounds } 

viewDidLayoutSubviews should be called when the device is rotated.

If it is not called, override this method and do it like

 override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) backgroundColor.frame = self.graphView.bounds } 
+4
source

Try entering gradient code in viewDidLayoutSubviews instead of viewDidLoad

When viewDidLoad is called, the views are not laid out (i.e. their final frames have not yet been set), so you only see a partial gradient coverage

+4
source

All Articles