0

static const CGRect screenRect = [[UIScreen mainScreen] bounds];
static const CGFloat screenWidth = screenRect.size.width;
static const CGFloat screenHeight = screenRect.size.height;

I understand that screen size is a runtime variable and not known at compile time. I've seen similar questions regarding arrays and other objects, but those don't directly pertain to this.

What is needed is a quick way to access the screen sizes, because thats how I'm doing all of the layout, and I don't want to redefine screenHeight and screenWidth in all my lazy loading property initializers, such as textFields and labels. I'm aware of self.view.frame.size but I'm looking for a more elegant solution.

So how can I go about having screenHeight and screenWidth widely accessible in the code for my app?

BeefJurky
  • 53
  • 1
  • 5
  • Like this? http://stackoverflow.com/a/14135265/294949 – danh Jun 28 '16 at 22:44
  • 1
    It is better to adopt autolayout as this will work in split screen mode on an iPad as well as full screen mode – Paulw11 Jun 28 '16 at 22:48
  • I've tried autolayout and I'm doing it all programmatically, so autolayout wasn't a very elegant solution – BeefJurky Jun 28 '16 at 22:50
  • 1
    Programatically or through IB AutoLayout is the way to go. It is much more elegant than calculations using screen width/height since these may break every time Apple releases a new device with a different screen size. It has a learning curve but is much better once you get through that. Otherwise you could make `screenWidth` and `screenHeight` computed variables – Paulw11 Jun 28 '16 at 22:52
  • I see, I'll look into it for my next project then. As for my current project and the original question though, do you mean making these values properties, and then overriding the getter? – BeefJurky Jun 28 '16 at 23:13
  • If you really want to go this way, you declare the variables without the `const` modifier, and you assign their values early in the app launch process. It's the wrong approach on many levels, though. – Avi Jun 29 '16 at 02:16

0 Answers0