如何在代码中实现自定义颜色方法 [英] How to implement a custom color method into code

查看:57
本文介绍了如何在代码中实现自定义颜色方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个包含customColor"代码的类,我想在我的代码中实现它,这样我就可以输入buttonOne.backgroundColor = [UIColor customColor].

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

在 .h 文件中,我有

In the .h file, I have

+ (UIColor*) customColor;

在 .m 文件中,我有

and in the .m file, I have

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

但是当我去ViewController.m"并输入

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

buttonOne.backgroundColor = [UIColor customColor]

我收到一个错误提示

没有已知的选择器类方法customColor

No known class method for selector customColor

我已经导入了 .h 文件.有没有我遗漏的步骤?

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

推荐答案

基本上,您试图创建一个类别,而没有向编译器正确声明这是一个 UIColor 类别.以下是如何创建类别的示例:

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:

将新的分类文件创建为新文件 > Cocoa Touch > Objective-C category.

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

我将示例命名为 UIColor+CustomColorCatagory.

UIColor+CustomColorCatagory.h中,修改为:

#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

UIColor+CustomColorCatagory.m中,修改为:

#import "UIColor+CustomColorCatagory.h"

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

然后在要使用这个方法的地方,添加#import "UIColor+CustomColorCatagory.h"简单地说:self.view.backgroundColor = [UIColor customColor];

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

这篇关于如何在代码中实现自定义颜色方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆