Miles
Miles

Reputation: 574

Views not scaling correctly unless the device is set in the storyboard (view as: iphone 5s/8/etc)

It's easiest to describe with screenshots (the "view as" I'm talking about is in the lower right of each image):

Simulator: iPhone 8, storyboard view as: iPhone 8 - works perfectly

enter image description here

Simulator: iPhone 8 plus, storyboard view as: iPhone 8 - doesn't work

enter image description here

Simulator: iPhone 8 plus, storyboard view as: iPhone 8 plus - works perfectly

enter image description here

Example of code that should work correctly, and does when the storyboard is set to that model phone, but doesn't otherwise:

gradientLayer.frame = CGRect(x: 0, y:0, width: self.view.bounds.width, height: self.view.bounds.height)
gradientLayer.colors = [Colors().bgRed.cgColor, Colors().mediumBlue.cgColor, Colors().highlitMedBlue.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.1, y: 0.1)
gradientLayer.endPoint = CGPoint(x: 1, y: 1)
self.view.layer.addSublayer(gradientLayer)

Other examples of failures are when I use view.convert(viewX, to: viewY), and it works/fails in the same circumstances as the above pictures.

What's going on here? Is it just the simulator that's wrong? Am I using autolayout incorrectly? Will this work if I tried it on actually phones, rather than the simulator?

Upvotes: 3

Views: 80

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try to put the frame line inside viewDidLayoutSubviews

override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews() 
  gradientLayer.frame = self.view.bounds 
}

It works perfectly for the simulator with same setting as storyboard , because the view size of it is considered for rendering until viewDidLayoutSubviews comes with correct size of the current simulator/device

Upvotes: 4

Cedan Misquith
Cedan Misquith

Reputation: 1154

You are setting the frames incorrectly. The width and height should be derived from self.view.frame

Try using

gradientLayer.frame = CGRect(x: 0, y:0, width: self.view.frame.width, height: self.view.frame.height)

If you wish to use self.view.bounds,

Then try

gradientLayer.frame = self.view.bounds

let me know if it works.

Upvotes: 1

Related Questions