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

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

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:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!