2013-10-19 75 views
0

我已經創建了一個類,其中包含要在代碼中實現的「customColor」的代碼,以便我可以只鍵入buttonOne.backgroundColor = [UIColor customColor]如何將自定義顏色方法實現爲代碼

在.h文件中,我有

+ (UIColor*) customColor; 

,並在.m文件,我有

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

,但是當我去 「ViewController.m」,然後輸入

buttonOne.backgroundColor = [UIColor customColor] 

我收到一個錯誤,說

的選擇customColor

沒有已知的類中的方法我已導入.h文件。我錯過了一個步驟嗎?

+0

您的自定義類是UIColor的類別嗎? – Luke

+0

它是UIColor – user2816600

+0

顯示導入和類別界面。 –

回答

4

基本上,你正在嘗試創建一個類別,但沒有正確地向編譯器聲明這是一個UIColor的類別。下面是如何創建類的實例:


創建新的產品類別的文件作爲新的文件>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];