Question

In my iOS app I have a constants.h class where I define kBorderWidth. For retina displays I would like this to be .5 so that borders are 1 pixel thick, and on non-retina displays I want it to be 1 so that it remains one pixel thick and not less. This is my code right now:

#define IS_RETINA ([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)] && ([UIScreen mainScreen].scale == 2.0))

#if __IS_RETINA == 1
    #define kBorderWidth .5
#else
    #define kBorderWidth 1
#endif

That compiles just fine but results in kBorderWidth being 1. How can I fix this so that it accomplishes that I want it to do?

Was it helpful?

Solution

The solution that I settled upon was the one suggested by Lanorkin which is to define it like this:

#define kBorderWidth (1.0 / [UIScreen mainScreen].scale)

That being future proof and simple as well as working within the constants.h file that I have already setup.

OTHER TIPS

Your "#define" Macro:

#define IS_RETINA ([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)] && ([UIScreen mainScreen].scale == 2.0))

defines some code that executes at run time, not at compile time.

Instead of doing:

#if __IS_RETINA == 1
    #define kBorderWidth .5
#else
    #define kBorderWidth 1
#endif

You should be setting a run time variable, such as:

static CGFloat gBorderWidth; // at the top of your .m file

or a property:

@property (readwrite) CGFloat borderWidth;

And then set it in your viewDidLoad or viewWillAppear methods:

if(([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)] && ([UIScreen mainScreen].scale == 2.0)))
{
    self.borderWidth = 0.5f;
} else {
    self.borderWidth = 1.0f;
}

Now that I realize you want to make this available to a number of view controllers (e.g. because it was originally in "constants.h"), why not create a decorator singleton class, which is always in existence for the life of your app and can control the appearance of your app via exposed properties, such as the "borderWidth" one.

So you could access it via something like:

 AppearanceUtilityClass *appearance = [AppearanceUtilityClass sharedInstance];
 CGFloat borderWidth = appearance.borderWidth;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top