Search code examples
iossprite-kitscreen-size

Best practice to store screen dimension for reuse in Spritekit game


I read out the screen dimensions of the current device in the following way:

[UIScreen mainScreen].bounds.size.height;
[UIScreen mainScreen].bounds.size.width;

I need this value very often in different classes of the game, so I want to avoid calculating these values again and again. What is the best practice to store and reuse these values in the game?


Solution

  • You cand store them in AppDelegate(.h), then call them wherever you need.

       @interface AppDelegate :UIResponder <UIApplicationDelegate> {
        ...
       }
       @property (nonatomic, assign) int MYSCREENHEIGHT;
       @property (nonatomic, assign) int MYSCREENWIDHT;
    

    In AppDelegate(.m) you should synthesize them, then:

        MYSCREENHEIGHT = [UIScreen mainScreen].bounds.size.height;
        MYSCREENWIDHT = [UIScreen mainScreen].bounds.size.width;      
    

    In other places just call them:

        AppDelegate *appDelGlobal = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        int myScreenHeight = appDelGlobal.MYSCREENHEIGHT;
        int myScreenwidth = appDelGlobal.MYSCREENWIDHT;
    

    You can store them in NSUserDefaults also, but this is not the case for you here.