view and scene not correct on iOS device rotation

128 views Asked by At

When doing a rotation, I'm getting an out of place view/scene. The viewWillTransition method is as below:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
{
  let newRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  let newSize = CGSize(width: size.width, height: size.height)

  self.view.frame = newRect

  let skView = self.view as! SKView      
  if let sceneNode = skView.scene as! GameScene? {      
    sceneNode.size = newSize

    sceneNode.position = CGPoint(x: self.view.frame.midX, y: self.view.frame.midY)

  }
}

Can someone please let me know what I'm doing wrong?

Thank you

2

There are 2 answers

0
AshokPolu On BEST ANSWER

Try this,

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let skView = self.view as! SKView
        if let sceneNode = skView.scene as! GameScene? {
            sceneNode.size = self.view.frame.size

            sceneNode.position = CGPoint(x: self.view.frame.midX, y: self.view.frame.midY)

        }
    }
0
feca On

Thx @AshokPolu!
I prefer this because the size will be animated along device rotate animation.

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    coordinator.animateAlongsideTransition(in: self.view, animation: { (_) in
        if let skView = self.view as? SKView, let scene = skView.scene as? GameScene {
            scene.size = self.view.frame.size
            scene.position = CGPoint(x: self.view.frame.midX, y: self.view.frame.midY)
        }
    }, completion: nil)
}