-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
  • 9,267
  • 17
  • 64
  • 105

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
  • 13,472
  • 2
  • 30
  • 51
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,318
  • 1
  • 11
  • 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
  • 515,959
  • 87
  • 875
  • 1,141
1

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

denicio
  • 562
  • 1
  • 7
  • 22