Global color definition

I want to define a global color that I can reuse for the downstream state for various user ui cells.

Not sure if this is the right way to do this, but ..

I defined a class called lightGreyUIColor that has this .h file -

#import <UIKit/UIKit.h> @interface lightGreyUIColor : UIColor + (UIColor*)lightGreyBGColor; @end 

and this. m file -

 #import "lightGreyUIColor.h" @implementation lightGreyUIColor + (UIColor*)lightGreyBGColor { return [UIColor colorWithRed:241.0/255.0 green:241/255.0 blue:241/255.0 alpha:1]; } @end 

I included the lightGreyUIColor.h file in the implementation file to represent the table and tried to refer to it as folows -

  cell.backgroundColor = [UIColor lightGreyBGColor]; 

What just gives rise to an unknown class or method error for lightgreyBGColor, where I am wrong, and is there a better way to implement a global style than this?

+6
source share
4 answers

You must create a category, not a subclass. This will expand the UIColor class and add your colors to it.

.h

 #import <UIKit/UIKit.h> @interface UIColor (CustomColors) + (UIColor *)myColorLightGreyBGColor; @end 

.m

 #import "UIColor+CustomColors.h" @implementation UIColor (CustomColors) + (UIColor *)myColorLightGreyBGColor { static UIColor *lightGreyBGColor; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ lightGreyBGColor = [UIColor colorWithRed:241.0 / 255.0 green:241.0 / 255.0 blue:241.0 / 255.0 alpha:1.0]; }); return lightGreyBGColor; } @end 

By defining colors this way and #importing categories, you can apply this custom color the way you already tried.

+24
source

How about a macro?

 #define DEFAULT_COLOR_BLUE [UIColor colorWithRed:.196 green:0.3098 blue:0.52 alpha:1.0] 

Put it in the appname_Prefix.pch file, or rather, the header file included in your prefix file

And it will look like this:

 cell.backgroundColor = DEFAULT_COLOR_BLUE; 
+10
source

Your class name lightGreyUIColor

Therefore, you need to use it as

 cell.backgroundColor = [lightGreyUIColor lightGreyBGColor]; 

Or you need to create a category on UIColor .


EDIT:

Your code [UIColor lightGreyBGColor] trying to find a method in UIColor , but you have subclassed UIColor into lightGrayUIColor .

As you call, it looks like you are intended for a category.

Side note: ClassName must be as lightGreyUIColor .

+2
source

You need a category. Read about it here.

In your case, you will have something like UIColor + Gray.h

 @interface UIColor (Grey) +(UIColor*) lightGreyBGColor; @end 

UIColor + Gray.m

 #import "UIColor+Grey.h" @implementation UIColor (Grey) +(UIColor*) lightGreyBGColor { //define color } 

Then in your controller you will refer to it as:

 cell.backgroundColor = [UIColor lightGreyBGColor]; 
+1
source

Source: https://habr.com/ru/post/958558/


All Articles