Use iOS category to create new Color

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 15:05:40

问题


I would like to create some new UIColors that are used in my app throughout. From time to time the RGB is slightly tweaked (the exact color shade is being debated)

Currently I have to create the new colors from RGB and the code is sprinkled all over and repeated.

Is there a better way where I can create a new color one and use that through out my app.

[UIColor myNewCustomRedColor]

What is the best pattern here - is Category the right choice - if so how? If no -what is the recommended approach.


回答1:


Category is a good choice for something like this. I usually just make a new .h/.m pair of files, MyCategories.h/MyCategories.m, that contains commonly used categories that you want everywhere.

MyCategories.h:

@interface UIColor (MyCategory)

+ (UIColor *)customRedColor;

@end

MyCategories.m

@implementation UIColor (MyCategory)

+ (UIColor *)customRedColor {
    return [UIColor redColor];
}

@end

You can either import the .h file wherever you need it, or you can stick the import in your MyApp-Prefix.pch file.




回答2:


One approach I've used on other projects is to create a ProjectStyle.h file, that has #defines for custom colors and other style related constants. You just need to import it.

Something like:

ProjectStyles.h

#define RED_HEADER_COLOR [UIColor colorWithRed:0.8f green:0.1f blue:0.1f alpha:0.9f]
#define RED_BACKGROUND_COLOR [UIColor colorWithRed:0.9f green:0.3f blue:0.1f alpha:1.0f]
#define PRIMARY_FONT [UIFont fontWithName:@"HelveticaNeue-Bold" size:12.0f]

You could also have a corresponding .m file if you wanted to create constant instances of some UIColor or UIFont objects, something like

ProjectStyles.m

+ (UIColor *) redHeaderColor 
{  return [UIColor colorWithRed:0.8f green:0.1f blue:0.1f alpha:0.9f];  }

+ (UIColor *) redBackgroundColor 
{  return [UIColor colorWithRed:0.9f green:0.3f blue:0.1f alpha:1.0f];  }

+ (UIFont *) primaryFont
{
    static UIFont *font = nil;
    if ( font == nil )
        font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:12.0f];
    return font;
}

And then of course expose those in the header

The other thing I like about a ProjectStyle kind of approach is that after a while you will want more custom things than just colors - custom fonts, custom line and shadows. Having a Style class or header to place all these things in gives you one place to look up what custom elements are already defined for all sorts of things, and a very obvious #import for later coders to follow back to you centralized well of custom information.

If you just place custom elements in categories then you end up with customization spread over several categories, and also the possibility (mostly remote) of category name collisions with other third party libraries.



来源:https://stackoverflow.com/questions/14917144/use-ios-category-to-create-new-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!