Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: How to define some default objects to be used anywhere?

Tags:

ios

There are many places in my app that needs to set the UIColor. I want to define the color somewhere that I can reuse it without writing the same line again, it's hard to keep track and maintain.

UIColor *myColor = [UIColor colorWithRed:0.1 green:0.3 blue:0.7 alpha:1];

I tried to make it like

#define myColor = [UIColor colorWithRed:0.1 green:0.3 blue:0.7 alpha:1];

and reuse myColor but it doesn't work. :/

Thanks!

like image 720
sonoluminescence Avatar asked Jan 27 '26 01:01

sonoluminescence


1 Answers

For your define, you could write:

#define myColor [UIColor colorWithRed:0.1 green:0.3 blue:0.7 alpha:1]

and where you use myColor, it'll be replaced outright with [UIColor colorWithRed:0.1 green:0.3 blue:0.7 alpha:1].

Alternatively, you could write a category on UIColor that provides a method that returns your colour.

Example:

@interface UIColor (MyColors)

+ (UIColor *)myAwesomeColor;

@end

@implementation UIColor (MyColors)

+ (UIColor *)myAwesomeColor
{
    return [UIColor colorWithRed:0.1 green:0.3 blue:0.7 alpha:1];
}

@end

You would then use this like [UIColor myAwesomeColor] wherever you need it, just like you do with [UIColor blackColor].

like image 122
Jasarien Avatar answered Jan 28 '26 18:01

Jasarien