How to implement a custom color method into code

倖福魔咒の 提交于 2019-12-13 05:15:55

问题


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];



来源:https://stackoverflow.com/questions/19470617/how-to-implement-a-custom-color-method-into-code

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