问题描述
假设我有一个 UIColor
,我希望在每个视图控制器中使用它来为它的标题/导航栏着色。我想知道宣布这种财产的最佳方式是什么。我是否应该将其声明为应用程序代理的成员?为全局属性创建一个模型类,并声明一个静态函数 +(UIColor)getTitleColor
?将 UIColor
对象传递给每个视图控制器?是否还有另一种方法,我没有描述,这被认为是最好的方式去做这件事? 很多方法来做到这一点。我喜欢通过将类别放在 UIColor
上: $ b
UIColor + MyAppColors.h
@interface UIColor(MyAppColors)
+(UIColor *)MyApp_titleBarBackgroundColor;
@end
UIColor + MyAppColors.m
#importUIColor + MyAppColors.h
@implementation UIColor(MyAppColors)
+ (UIColor *)MyApp_titleBarBackgroundColor {
static UIColor * color;
static dispatch_once_t once;
dispatch_once(& once,^ {
color = [UIColor colorWithHue:0.2 saturation:0.6 brightness:0.7 alpha:1];
});
返回颜色;
}
@end
然后我可以使用它在任何需要标题栏背景颜色的文件中导入 UIColor + MyAppColors.h
,然后像这样调用它:
myBar.tintColor = [UIColor MyApp_titleBarBackgroundColor];
Suppose I have a UIColor
that I want to use across every view controller to tint it's title/navigation bar. I was wondering what is the best way to declare such a property. Should I declare it as a member of the application delegate? Create a model class for global properties, and declare a static function + (UIColor)getTitleColor
? Pass the UIColor
object to every view controller? Is there another method that I did not describe, that is viewed as being the best way to go about this?
There are lots of ways to do this. I like to do it by putting a category on UIColor
:
UIColor+MyAppColors.h
@interface UIColor (MyAppColors)
+ (UIColor *)MyApp_titleBarBackgroundColor;
@end
UIColor+MyAppColors.m
#import "UIColor+MyAppColors.h"
@implementation UIColor (MyAppColors)
+ (UIColor *)MyApp_titleBarBackgroundColor {
static UIColor *color;
static dispatch_once_t once;
dispatch_once(&once, ^{
color = [UIColor colorWithHue:0.2 saturation:0.6 brightness:0.7 alpha:1];
});
return color;
}
@end
Then I can use it by importing UIColor+MyAppColors.h
in any file that needs the title bar background color, and calling it like this:
myBar.tintColor = [UIColor MyApp_titleBarBackgroundColor];
这篇关于在iOS应用程序中声明全局变量的最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!