Where should I store 30+ UIColors for quick reference?

后端 未结 2 1235
忘了有多久
忘了有多久 2021-01-17 01:01

I want to have 30+ constant UIColors so I can easily access them in my app. I\'d like to be able to do something like this:

 [self setBackgroundColor:[UICol         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-17 01:40

    Define a category for UIColor:

    In UIColor+MyColors.h:

    @interface UIColor (MyColors)
    
    + (UIColor *)skyColor;
    + (UIColor *)dirtColor;
    // and the rest of them
    
    @end
    

    In UIColor+MyColors.m:

    @implementation UIColor (MyColors)
    
    + (UIColor *)skyColor {
        static UIColor color = nil;
        if (!color) {
            // replace r, g, and b with the proper values
            color = [UIColor colorWithRed:r green:g blue:b alpha:1];
        }
    
        return color;
    }
    
    + (UIColor *)dirtColor {
        static UIColor color = nil;
        if (!color) {
            // replace r, g, and b with the proper values
            color = [UIColor colorWithRed:r green:g blue:b alpha:1];
        }
    
        return color;
    }
    
    // and the rest
    
    @end
    

    Edit:

    As Martin R points out, a more modern approach to initializing the static color variable would be:

    + (UIColor *)skyColor {
        static UIColor color = nil;
        static dispatch_once_t predicate = 0;
    
        dispatch_once(&predicate, ^{
            // replace r, g, and b with the proper values
            color = [UIColor colorWithRed:r green:g blue:b alpha:1];
        });
    
        return color;
    }
    

    This may actually be overkill in this case since there is no bad side-effect if two threads happen to initialize the nil static variable at the same time using the original code. But it is a better habit to use dispatch_once.

提交回复
热议问题