有時(shí)我們?cè)谟玫?UITextField 的屬性的時(shí)候,需要做出一些不常規(guī)的屬性观腊,例如改變placeholder 的字體或顏色啊
方法一邑闲、runtime 獲取類的成員變量,拿到相應(yīng)的變量名用KVO 設(shè)置
unsigned int count = 0;
// 拷貝出所有的成員變量列表
Ivar *ivars = class_copyIvarList([UITextField class], &count);
for (int i = 0; i < count; i++) {
// 取出成員變量
Ivar ivar = ivars[i];
// 打印成員變量名字
NSLog(@"%s", ivar_getName(ivar));
}
// 釋放
free(ivars);
// 有很多就不不一列舉啦
/**
_borderStyle | _leftViewMode | _padding
_disabledBackgroundView | _placeholderLabel
_suffixLabel | _prefixLabel
*/
使用 KOV恕沫,@"_placeholderLabel.textColor" & @"_placeholderLabel.font"
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont systemFontOfSize:20] forKeyPath:@"_placeholderLabel.font"];
PS:
// setValue:forKey: :傳入NSString屬性的名字;
// setValue:forKeyPath:傳入NSString屬性的路徑监憎,xx.xx形式;
方法二、利用富文本設(shè)置attributedPlaceholder
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Placeholder Text"
attributes:@{
NSForegroundColorAttributeName: [UIColor redColor],
NSFontAttributeName : [UIFont systemFontOfSize:16]
}
];
方法三婶溯、自定義UITextField 重寫drawPlaceholderInRect方法
– textRectForBounds: //重寫來(lái)重置文字區(qū)域
– drawTextInRect: //改變繪文字屬性.重寫時(shí)調(diào)用super可以按默認(rèn)圖形屬性繪制,若自己完全重寫繪制函數(shù),就不用調(diào)用super了.
– placeholderRectForBounds: //重寫來(lái)重置占位符區(qū)域
– drawPlaceholderInRect: //重寫改變繪制占位符屬性.重寫時(shí)調(diào)用super可以按默認(rèn)圖形屬性繪制,若自己完全重寫繪制函數(shù)偷霉,就不用調(diào)用super了
– borderRectForBounds: //重寫來(lái)重置邊緣區(qū)域
– editingRectForBounds: //重寫來(lái)重置編輯區(qū)域
– clearButtonRectForBounds: //重寫來(lái)重置clearButton位置,改變size可能導(dǎo)致button的圖片失真
例如 改變顏色 或者是 placeholder 位置
///控制placeHolder的顏色迄委,向右縮50
- (void)drawPlaceholderInRect:(CGRect)rect
{
[[self placeholder] drawInRect:rect withAttributes:
@{
NSForegroundColorAttributeName: [UIColor redColor],
NSFontAttributeName:[UIFont systemFontOfSize:20]
}
];
}
//控制placeHolder的位置,向右縮50
-(CGRect)placeholderRectForBounds:(CGRect)bounds
{
CGRect inset = CGRectMake(bounds.origin.x + 50, bounds.origin.y, bounds.size.width -50, bounds.size.height);
return inset;
}
總的來(lái)說(shuō)类少,推薦方法二利用富文本設(shè)置attributedPlaceholder叙身,簡(jiǎn)單明了,不宜出錯(cuò)硫狞。