2011-05-27 41 views
17

我有一個3 UITextField,其中包含佔位符文本集。在其中一個UITextField我希望佔位符文本爲紅色。如何繼承UITextField並覆蓋drawPlaceholderInRect以更改佔位符顏色

現在谷歌搜索後,似乎做到這一點的最好方法是繼承UITextField並覆蓋drawPlaceholderInRect

如何進行子類化和重寫drawPlaceholderInRect?我還沒有找到任何代碼示例或教程,我是新來的Objective-C和iOS開發,所以找到解決它很棘手。

答:

創建了一個名爲CustomUITextFieldPlaceholder一個新的Objective-C類的子類UITextField。在CustomUITextFieldPlaceholder.m把下面的代碼

@implementation CustomUITextFieldPlaceholder 

- (void)drawPlaceholderInRect:(CGRect)rect { 
    // Set colour and font size of placeholder text 
    [[UIColor redColor] setFill]; 
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:12]]; 
} 

@end 

爲了落實上述項目中的

#import "CustomUITextFieldPlaceholder.h" 

IBOutlet CustomUITextFieldPlaceHolder *txtName; 

注:這工作,我認爲這是正確的做法,但我有沒有完全測試它。希望這個例子能幫助別人解決我的問題。

編輯:

改變

[[UIColor redColor] setFill]; 

[[UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:0.7] setFill]; 

,這樣我可以設置不透明度爲70%,以模仿默認佔位符。

+0

子類並重寫該方法不會幫助你改變字體顏色,它只是讓你自定義顯示的佔位符在哪裏。 – 2011-05-27 11:23:05

+0

也許你可以嘗試覆蓋這個委託方法 - '(void)drawPlaceholderInRect:(CGRect)rect' – Hisenberg 2011-05-27 11:27:52

回答

7

要回答你的具體問題,這是子類是如何工作的:

// CustomTextField.h 
@interface CustomTextField : UITextField { 
} 
@end 

下面是如何重寫方法:

@implementation 
- (CGRect)placeholderRectForBounds:(CGRect)bounds { 
    return CGRectMake(x,y,width,height); 
} 
@end 

但是我不認爲這是你想要覆蓋的方法。我認爲這是你在找什麼:

@implementation 
- (void)drawPlaceholderInRect:(CGRect)rect { 
    // Your drawing code. 
} 
@end 
+0

感謝您的回覆@Erik,您的權利我的意思是drawPlaceholderInRect。我將創建代碼來做到這一點,手指劃過:) – 2011-05-27 11:52:49

+0

但創建類後,在實現中添加此方法我無法獲得我的文本字段佔位符顏色的變化 – 2016-04-05 05:55:47

0
[yourTextfield setValue:[UIColor colorWithRed:62.0/255.0f green:62.0/255.0f blue:62./255.0f alpha:1.0f] forKeyPath:@"_placeholderLabel.textColor"]; 

我想這將是有益的

+0

該下劃線使它看起來很私密... – 2013-05-23 08:02:12