简体   繁体   中英

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
    } 
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM