假设我有一个 UIColor
,我想在每个 View Controller 中使用它来为它的标题/导航栏着色。我想知道申报此类属性(property)的最佳方式是什么。我应该将其声明为应用程序委托(delegate)的成员吗?为全局属性创建一个模型类,并声明一个静态函数+ (UIColor)getTitleColor
?将 UIColor
对象传递给每个 View Controller ?有没有我没有描述的另一种方法,它被认为是解决这个问题的最佳方法?
最佳答案
有很多方法可以做到这一点。我喜欢通过在 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
然后我可以通过在任何需要标题栏背景颜色的文件中导入 UIColor+MyAppColors.h
来使用它,并像这样调用它:
myBar.tintColor = [UIColor MyApp_titleBarBackgroundColor];
关于objective-c - 在 iOS 应用程序中声明全局变量的最佳做法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12357105/