Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

viewWillLayoutSubviews in Swift

Tags:

swift

I'm trying to translate SKScene * scene = [GameScene sceneWithSize:skView.bounds.size]; into swift but I get the error

'sceneWithSize' is unavailable: use object construction 'SKScene(size:)'.

I am using viewWillLayoutSubviews and cutting out the viewDidLoad() because it does not give correct dimensions for the screen dimensions of the device I choose. It actually makes me question why viewDidLoad() exists at all?

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews();
    let skView = self.view as SKView;
    if skView.scene != nil {
        skView.showsFPS = true;
        skView.showsNodeCount = true;
        skView.showsPhysics = true;
        // Create and configure the scene

        let scene:SKScene = GameScene.sceneWithSize(skView.bounds.size); // ERROR MESSAGE!
        //    Objective-C code in next 2 lines
        //    SKScene * scene = [GameScene sceneWithSize:skView.bounds.size];
        //    scene.scaleMode = SKSceneScaleModeAspectFill;

        // Present Scene
        skView.presentScene(scene)
    }
}
like image 937
baskInEminence Avatar asked Dec 04 '14 07:12

baskInEminence


People also ask

When to use viewDidLayoutSubviews?

viewDidLayoutSubviews. This method is called when after layout subViews. It means that the view is updated and lays out their bounds and frames. You can override this method if you need some implementation when after updated views.

How often is viewDidLayoutSubviews called?

In another word, viewDidLayoutSubviews is called every time the view is updated, rotated or changed or it's bounds change . The keyword here is bounds change. But know that with viewDidLayoutSubviews , it only take places after all the auto layout or auto resizing calculations on the views have been applied.

What is a UIViewController?

The UIViewController class defines the methods and properties for managing your views, handling events, transitioning from one view controller to another, and coordinating with other parts of your app.

What is layoutIfNeeded in Swift?

layoutIfNeeded()Lays out the subviews immediately, if layout updates are pending.


1 Answers

Try changing

let scene:SKScene = GameScene.sceneWithSize(skView.bounds.size);

by

let scene:SKScene = GameScene(size: skView.bounds.size);

Hope this helps ;)

like image 105
smorollon Avatar answered Nov 15 '22 12:11

smorollon