【问题标题】:Color Variables in Objective CObjective C 中的颜色变量
【发布时间】:2015-03-29 07:05:29
【问题描述】:
如何在 Obj C 中设置和重用颜色变量?我正在尝试设置一个可重复使用的颜色值,如下所示:
Change background color with a variable iOS
但我没有成功。
UIColor *lightGrayHeader = [UIColor colorWithRed:246/255.f green:239/255.f blue:239/255.f alpha:1.0];
self.view.backgroundColor = [UIColor lightGrayHeader];
返回错误:“Initializer element is not a compile-time constant。”
感谢您的想法!
【问题讨论】:
标签:
ios
objective-c
user-interface
colors
【解决方案1】:
你定义的是一个局部变量。它是这样使用的:
UIColor *lightGrayHeader = [UIColor colorWithRed:246/255.f green:239/255.f blue:239/255.f alpha:1.0];
self.view.backgroundColor = lightGrayHeader;
如果您想在 UIColor 上使用静态方法来获取颜色,您可以这样做:
@interface UIColor (MyColours)
+ (instancetype)lightGrayHeader;
@end
@implementation UIColor (MyColours)
+ (instancetype)lightGrayHeader {
return [self colorWithRed:246/255.f green:239/255.f blue:239/255.f alpha:1.0];
}
@end
然后只要导入UIColor (MyColours) 标头,就可以使用:
self.view.backgroundColor = [UIColor lightGrayHeader];
【解决方案2】:
既然您已经创建了lightGrayHeader 颜色,请使用它:
UIColor *lightGrayHeader = [UIColor colorWithRed:246/255.f green:239/255.f blue:239/255.f alpha:1.0];
self.view.backgroundColor = lightGrayHeader;
self.otherView.backgroundColor = lightGrayHeader;
...
【解决方案3】:
UIColor *lightGrayHeader = [UIColor colorWithRed:246/255.f green:239/255.f blue:239/255.f alpha:1.0];
self.view.backgroundColor = [UIColor lightGrayHeader]; // error
它是一个变量,而不是 UIColor 的方法:
self.view.backgroundColor = lightGrayHeader;
【解决方案4】:
它就像这样self.view.backgroundColor = lightGrayHeader;