Objective C 中的颜色变量
Color Variables in Objective C
如何在 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];
Returns 一个错误:"Initializer element is not a compile-time constant."
谢谢你的想法!
它是这样工作的self.view.backgroundColor = lightGrayHeader;
由于您已经创建了 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;
...
你定义的是局部变量。它是这样使用的:
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];
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;
如何在 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];
Returns 一个错误:"Initializer element is not a compile-time constant."
谢谢你的想法!
它是这样工作的self.view.backgroundColor = lightGrayHeader;
由于您已经创建了 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;
...
你定义的是局部变量。它是这样使用的:
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];
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;