在项目中我们有时会遇到让我们改变placeholder的颜色,简单介绍一下改变placeholder的颜色的几种方法
利用属性字符串,UITextField有这样一个属性attributedPlaceholder,可以让我们定制placeholder的属性
<pre>let placeHolderTextAttr = NSMutableAttributedString(string: "请输入您的名字");
placeHolderTextAttr.addAttributes([NSForegroundColorAttributeName:UIColor.redColor()], range: NSMakeRange(0, placeHolderTextAttr.length))
self.textField.attributedPlaceholder = placeHolderTextAttr;
</pre>-
如果用xib或SB的话,可以在xib中设置user Defined Runtime Attributes
keyPath设置成_placeholderLabel.textColor type设置成Color,需要注意的是,设置之前一定要先选中textField
用extension和KVC去做,由于以上2种写法只针对某一个textField,如果有多个textField需要设置的话,显得比较麻烦,用extension的话就简单多了
<pre>
extension UITextField{
@IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
if let placeHolderLabel = self.valueForKey("placeholderLabel") as? UILabel {
placeHolderLabel.textColor = newValue!;
} ;
}
}
}</pre>在OC中extension是不能添加实现的这时我们可以用分类去实现这个功能
<pre>
@interface UITextField (SCPlaceHolder)
@property (nonatomic,strong)IBInspectable UIColor *sc_placeHolderColor;
@end
@implementation UITextField (SCPlaceHolder)
<code>-</code> (void)setSc_placeHolderColor:(UIColor *)sc_placeHolderColor{
((UILabel *)[self valueForKey:@"placeholderLabel"]).textColor = sc_placeHolderColor;
}
<code>-</code> (UIColor *)sc_placeHolderColor{
return ((UILabel *)[self valueForKey:@"placeholderLabel"]).textColor;
}
@end
</pre>