設(shè)置UITextField的placeholder的顏色代碼片段:
textField.placeholder = @"請輸入用戶名!";
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
或者直接在iOS6.0之后提供的attributedPlaceholder屬性:
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
NSString *holderText = @"請輸入密碼困曙!";
NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:holderText];
[placeholder addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(0, holderText.length)];
[placeholder addAttribute:NSFontAttributeName
value:[UIFont boldSystemFontOfSize:16]
range:NSMakeRange(0, holderText.length)];
textField.attributedPlaceholder = placeholder;
[cell.contentView addSubview:textField];
與上面那段代碼是一樣的效果。
_placeholderLabel說明
(lldb) po [textField valueForKey:@"_placeholderLabel"]
<UITextFieldLabel: 0x13fe835f0; frame = (0 0; 0 0); text = '請輸入密碼!'; opaque = NO; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x13fe855f0>>
其實_placeholderLabel就是UITextFieldLabel類型夹囚,這是在有placeholder的情況下打印出來的,但是為什么知道內(nèi)部叫\(zhòng) _placeholderLabel呢?根據(jù)蘋果的命名規(guī)范,猜測出來的臊岸,然后測試能否獲取到。其實可以通過Runtime中獲取類的屬性來拿到這個私有屬性尊流。這不算私有API帅戒,這是利用KVC獲取的,雖然蘋果并不希望我們這么做奠旺,但是可以正常上架(在很多個App里使用過)蜘澜。
說明
iOS6.0之后,有attributedPlaceholder屬性响疚,因此可以直接通過它設(shè)置。
在iOS6.0之前瞪醋,可以通過KVC來設(shè)置_placeholderLabel的屬性值忿晕。