-4

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:

Change background color with a variable iOS

but am unsuccessful.

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

 self.view.backgroundColor = [UIColor lightGrayHeader];

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

Thanks for your ideas!

Community
  • 1
  • 1
Nick B
  • 8,802
  • 13
  • 59
  • 103

4 Answers4

5

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;

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

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

self.view.backgroundColor = [UIColor lightGrayHeader];
Ian MacDonald
  • 12,599
  • 2
  • 26
  • 46
4

Since you've already created the lightGrayHeader color, just use it:

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;
...
Nicolas B.
  • 1,288
  • 1
  • 10
  • 20
2
UIColor *lightGrayHeader = [UIColor colorWithRed:246/255.f green:239/255.f blue:239/255.f alpha:1.0];
self.view.backgroundColor = [UIColor lightGrayHeader]; // error

It's a variable, not a method of UIColor:

self.view.backgroundColor = lightGrayHeader;
matt
  • 485,702
  • 82
  • 818
  • 1,064
1

It works like this self.view.backgroundColor = lightGrayHeader;

denicio
  • 522
  • 1
  • 6
  • 22