我有一個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%,以模仿默認佔位符。
子類並重寫該方法不會幫助你改變字體顏色,它只是讓你自定義顯示的佔位符在哪裏。 – 2011-05-27 11:23:05
也許你可以嘗試覆蓋這個委託方法 - '(void)drawPlaceholderInRect:(CGRect)rect' – Hisenberg 2011-05-27 11:27:52