iosswiftuiviewcontrollersprite-kitskview

Center SKView in UIViewController: Swift


I'm using the following code to load an SKView on the view controller. However, when you first load the app the buttons, labels etc. In the scene show up at the very bottom left. But, in the game when you return to the scene, it's centered, how could I fix this?

import UIKit
import SpriteKit

class ViewController: UIViewController {

    override func loadView() {
        self.view = SKView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let scene = StartScene(size: view.bounds.size)
        let skView = view as! SKView
        skView.ignoresSiblingOrder = true
        scene.scaleMode = .resizeFill
        skView.presentScene(scene)

    }

    override func prefersStatusBarHidden() -> Bool {
        return true
    } 
}

Solution

  • I suggest moving the your code from viewDidLoad to

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    
        let scene = StartScene(size: view.bounds.size)
        let skView = view as! SKView
        skView.ignoresSiblingOrder = true
        scene.scaleMode = .resizeFill
        skView.presentScene(scene)
    }
    

    viewDidLayoutSubviews will be called whenever the view reposition itself or get resized