Ios 基于BOOL定义常量

Ios 基于BOOL定义常量,ios,macros,constants,retina-display,Ios,Macros,Constants,Retina Display,在我的iOS应用程序中,我有一个constants.h类,我在其中定义kBorderWidth。对于视网膜显示器,我希望它是.5,这样边框就有1个像素厚,而对于非视网膜显示器,我希望它是1,这样它就有1个像素厚,而不是更少。这是我现在的代码: #define IS_RETINA ([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)] && ([UIScreen m

在我的iOS应用程序中,我有一个constants.h类,我在其中定义kBorderWidth。对于视网膜显示器,我希望它是.5,这样边框就有1个像素厚,而对于非视网膜显示器,我希望它是1,这样它就有1个像素厚,而不是更少。这是我现在的代码:

#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
这可以很好地编译,但会导致kBorderWidth为1。我怎样才能解决这个问题,使它达到我想要的效果

您的“
#define
”宏:

定义一些在运行时而不是编译时执行的代码

而不是做:

#if __IS_RETINA == 1
    #define kBorderWidth .5
#else
    #define kBorderWidth 1
#endif
您应该设置一个运行时变量,例如:

static CGFloat gBorderWidth; // at the top of your .m file
或财产:

@property (readwrite) CGFloat borderWidth;
然后在viewDidLoad或ViewWillAspect方法中进行设置:

if(([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)] && ([UIScreen mainScreen].scale == 2.0)))
{
    self.borderWidth = 0.5f;
} else {
    self.borderWidth = 1.0f;
}
既然我意识到你想让很多视图控制器都可以使用它(例如,因为它最初在“
constants.h
”)中,为什么不创建一个decorator singleton类,它在你的应用程序的生命周期中一直存在,并且可以通过公开的属性(例如“
borderWidth
”一个

因此,您可以通过以下方式访问它:

 AppearanceUtilityClass *appearance = [AppearanceUtilityClass sharedInstance];
 CGFloat borderWidth = appearance.borderWidth;

我决定的解决方案是由Lanorkin提出的,它是这样定义的:

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

这是未来的证明,而且很简单,并且在我已经设置的constants.h文件中工作。

我开始了类似的回答,然后意识到,
kBorderWidth
是在constants.h文件中定义的,这意味着该变量应该在导入.h的任何类中都可用。您的解决方案只适用于单个.m文件.bleah…那太恶心了。好吧。我会试着修改一下我的答案。虽然我同意Michael的答案,而且通常最好使用singleton而不是#define来定义这种情况,但你可能想使用类似于
#define kBorderWidth(1.0/[UIScreen mainScreen].scale)
的东西,它甚至可以为futuretina显示器提供1px的性能。
#define kBorderWidth (1.0 / [UIScreen mainScreen].scale)