Audus
Audus

Reputation: 195

How can I obtain an SKScene's size in `didMove(to view: SKView)` when setting scaleMode to resizeFill?

I need the SKScene's size to make some initial calculations in my didMove method. When I use the SKSceneScaleMode case of resizeFill to set the scaleMode of my gameScene the self.size values are (0, 0) in the gameScene's didMove method. When I query the size in other methods such as touchesBegan the values are what would be expected (non-zero values that match the size of the scene). This issue only occurs when setting the gameScene.scalemode to resizeFill before presenting the scene. Any other case of SKSceneScaleMode works fine.

Here is the example code

import SpriteKit

class GameViewController: UIViewController {
    override func loadView() {
        self.view = SKView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let skView = view as! SKView
        let gameScene = GameScene(size: UIScreen.main.bounds.size)
        gameScene.scaleMode = .resizeFill
        skView.presentScene(gameScene)
    }
}

class GameScene: SKScene, SKPhysicsContactDelegate {
    override func didMove(to view: SKView) {
        print(self.size) // self.size == (0,0)
        // ...calculations using self.size
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            print(self.size) // self.size has expected, non-zero valeus
     }
}

I am not using storyboards or sks files. Here is what the appDelegate looks like

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow()
        window?.makeKeyAndVisible()
        let gameViewController = GameViewController()
        window?.rootViewController = gameViewController
        return true
    }
}

Upvotes: 2

Views: 301

Answers (1)

Knight0fDragon
Knight0fDragon

Reputation: 16837

you aren't calling super.didMove(to:view). Try that first, if that doesn't work, then do:

override func didMove(to view: SKView) {
    super.didMove(to:view)
    DispatchQueue.main.async{
        print(self.size)
    }
}

What this will do is tell the GCD to run this block shortly after your function ends.

Upvotes: 1

Related Questions