Whats the correct way, using “init” or “didmove”?

2019-04-28 04:36发布

Language: Swift 3.0 --- IDE : Xcode 8.0 beta 2 --- Project : iOS Game (SpriteKit)

I create a game for iOS and i know Apple is really strict with their rules to accept the app/game. So i want to know which is the correct way to setup a game.

I learned from google to create a new SpriteKit Project and do the following setup :

In GameViewController.swift clear viewDidLoad() and add all this :

override func viewDidLoad() {
    super.viewDidLoad()
    let skView = self.view as! SKView

    let scene = GameScene(size: skView.bounds.size)
    scene.scaleMode = .aspectFit

    skView.presentScene(scene)
}

In GameScene.swift delete everything and leave this code :

import SpriteKit

class GameScene: SKScene {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(size: CGSize) {
        super.init(size: size)
        // add all the code of the game here...
    }

}

and develop my game inside override init

But I think thats actually wrong to start the game with init. And that the right way is to use the didMove() method. So should the code be written inside here? :

override func didMove(to view: SKView) {
    <#code#>
}

Does anyone know which one is the correct way? And why? Also if its wrong the way i do it, can you explain me how to use didMove method?

Don't know if this is a silly question just bothered me that using init is wrong and wanted to ask if someone knows more about this.

1条回答
欢心
2楼-- · 2019-04-28 05:01

Overriding the SKScene init

You can override the initializers of SKScene like described by @Knight0fDragon

class GameScene : SKScene {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()             
    }

    override init() {
        super.init()
        setup()
    }

    override init(size: CGSize) {
        super.init(size: size)
        setup()
    }

    func setup()
    {
        // PUT YOUR CODE HERE

    }
}

Or you can use the didMove(to:)

class GameScene: SKScene {
    override func didMove(to view: SKView) {
        super.didMove(to: view)
        // PUT YOUR CODE HERE <-----
    }
}

The init is called only when the scene is initialised. The didMove is called when the scene is presented into the view.

查看更多
登录 后发表回答