How to implement a custom color method into code

2019-09-09 03:20发布

问题:

I have created a class containing code for a "customColor" that I want to implement into my code so that I can just type buttonOne.backgroundColor = [UIColor customColor].

In the .h file, I have

+ (UIColor*) customColor;

and in the .m file, I have

+ (UIColor*) customColor {
    return [UIColor colorWithRed:0.643 green:0.643 blue:0.643 alpha:1];
}

but when I go to "ViewController.m" and type in

buttonOne.backgroundColor = [UIColor customColor]

I get an error saying

No known class method for selector customColor

I have imported the .h file. Is there a step I have missed out?

回答1:

Basically you're trying to create a category without correctly declaring to the compiler this is a category of UIColor. Here is an example of how to create your category:


Create the new catagory file as a new file > Cocoa Touch > Objective-C category.

I named my example UIColor+CustomColorCatagory.

In UIColor+CustomColorCatagory.h, change it to:

#import <UIKit/UIKit.h>

@interface UIColor (CustomColorCatagory)   //This line is one of the most important ones - it tells the complier your extending the normal set of methods on UIColor
+ (UIColor *)customColor;

@end

In UIColor+CustomColorCatagory.m, change it to:

#import "UIColor+CustomColorCatagory.h"

@implementation UIColor (CustomColorCatagory)
+ (UIColor *)customColor {
    return [UIColor colorWithRed:0.643 green:0.643 blue:0.643 alpha:1];
}
@end

Then in the places you want to use this method, add #import "UIColor+CustomColorCatagory.h" and simply: self.view.backgroundColor = [UIColor customColor];