Carl Jonsson
Carl Jonsson

Reputation: 3

Swift - Why is UIScreen.main.bounds behaving differently on different devices?

I am trying to create a game for IOS using SpriteKit. My problem is that different devices outputs different things. This is the code I try:

var testPath = CGRect(
   x: 0,
   y: 0,
   width: UIScreen.main.bounds.width * 2,
   height: UIScreen.main.bounds.height * 2
)
var testFill = SKShapeNode(path: CGPath(rect: testPath, transform: nil))

testFill.fillColor = UIColor.black
addChild(testFill)

For iPhone 7 this works perfectly. For iPhone 5 I get extra space on top and to the right, the same result for Ipads. For iPhone 7+, however, I go outside the screen.

My first question is, why do I need to take main.bounds.height * 2 to cover the screen vertically. Shouldn't * 1 be enough? Secondly and more importantly, why do I get so different results on different devices?

Upvotes: 0

Views: 2268

Answers (3)

Pavel L.
Pavel L.

Reputation: 41

Maybe you should check your info.plst to see the line about the launch screen: https://stackoverflow.com/a/62749138/13433324

Upvotes: 1

Florian Burel
Florian Burel

Reputation: 3456

You will face many problems should you pursue in this direction!

You should not use the screen size but your view controller's view bounds. Doing so will avoid size problems, should your app be used in multitask or otherwise...

override func viewDidLoad() {
    super.viewDidLoad()
    let skView = SKView(frame: self.view.bounds) 
    view.addSubview(skView);
    let scene = MyScene(size: view.bounds.size) // <- construct your scene with the screen size
    skView.presentScene(scene)
  }

You can then fill your scene and use the size value to layout your nodes.

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

1- According to game logic play space should have more size than screen , so sprites come across from different position , if you set it to only *1 (will fill the entire screen including the statusBar) , added sprite will show in screen instead of bouncing from left to right / bottom to top

2- Every device has it's own different screen size , so it's size * 2 will also be different

Upvotes: 0

Related Questions