目标C中的颜色变量

目标C中的颜色变量

本文介绍了目标C中的颜色变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Obj C中设置和重用颜色变量?我正在尝试设置一个可重复使用的颜色值,例如:

How do I set and reuse a color variable in Obj C? I am trying to set a reusable color value as in this question:

但不成功。

 UIColor *lightGrayHeader = [UIColor colorWithRed:246/255.f green:239/255.f blue:239/255.f alpha:1.0];

 self.view.backgroundColor = [UIColor lightGrayHeader];

返回错误: Initializer元素不是编译时常量。

Returns an error: "Initializer element is not a compile-time constant."

感谢您的想法!

推荐答案

您定义的是局部变量。它的用法如下:

What you have defined is a local variable. It is used like this:

UIColor *lightGrayHeader = [UIColor colorWithRed:246/255.f green:239/255.f blue:239/255.f alpha:1.0];
self.view.backgroundColor = lightGrayHeader;

如果要在 UIColor 获取颜色,您可以执行以下操作:

If you want to use a static method on UIColor to fetch a colour, you could do this:

@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)头,您可以使用:

And then as long as you import the UIColor (MyColours) header, you could use:

self.view.backgroundColor = [UIColor lightGrayHeader];

这篇关于目标C中的颜色变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:35