Iphone – How to call [[UIScreen mainScreen] scale] in a universal app for the iphone and ipad

ios4ipadiphone

I'm making a universal app that will run on both the ipad and the iphone. So far so good, but I have just updated my SDK to ios4 and am wanting to call [[UIScreen mainScreen] scale] (scale is not in the 3.2 sdk and the ipad doesn't have ios4 yet).

I know that I can call [[UIScreen mainScreen] respondsToSelector:@selector(scale)] to find out if I can call it, but I still need to have the function call (and be able to access the return value) in my code so that it can run on the iphone.

EDITED: To be clear, my problem is that there is an error when using the code [[UIScreen mainScreen] scale] when building for 3.2 SDK. This error is "Incompatible types in assignment". So I need to be able to still call this function for 4.0 SDK but still have the project build for 3.2 SDK.

Best Answer

Well, you could just wrap every call to it in an if statement, like so:

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    //do scale stuff here
}

But a better way (which might require restructuring your whole app, though) is to have separate view controllers for iPad and iPhone.

To get the scale of the device for a cross platform view or something, you could do like this:

CGFloat scale;
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    scale=[[UIScreen mainScreen] scale];
} else {
    scale=1; //only called on iPad.
}

To avoid typing this every time, you could declare a category on UIScreen, which uses this code inside a -realScale method or something.

All of these methods require setting the base SDK to 4.0 (so that you can access the 4.0 APIs) and the minimum iPhone deployment target to 3.2 (so it will run on iPad)

Related Topic