0%

如何改变UITextField的placeholder的颜色

在项目中我们有时会遇到让我们改变 placeholder 的颜色,简单介绍一下改变 placeholder 的颜色的几种方法

  1. 利用属性字符串,UITextField 有这样一个属性 attributedPlaceholder,可以让我们定制 placeholder 的属性
1
let placeHolderTextAttr = NSMutableAttributedString(string: "请输入您的名字");
2
placeHolderTextAttr.addAttributes([NSForegroundColorAttributeName:UIColor.redColor()], range: NSMakeRange(0, placeHolderTextAttr.length))
3
self.textField.attributedPlaceholder = placeHolderTextAttr;
  1. 如果用 xib 或 SB 的话,可以在 xib 中设置 user Defined Runtime Attributes
    keyPath 设置成_placeholderLabel.textColor type 设置成 Color,需要注意的是,设置之前一定要先选中 textField
    屏幕快照 2016-09-09 07.35.37.png

  2. 用 extension 和 KVC 去做,由于以上 2 种写法只针对某一个 textField,如果有多个 textField 需要设置的话,显得比较麻烦,用 extension 的话就简单多了

1
extension UITextField{
2
    @IBInspectable var placeHolderColor: UIColor? {
3
        get {
4
            return self.placeHolderColor
5
        }
6
        set {
7
            if let placeHolderLabel = self.valueForKey("placeholderLabel") as? UILabel {
8
                placeHolderLabel.textColor = newValue!;
9
            } ;
10
        }
11
    }
12
}
  1. 在 OC 中 extension 是不能添加实现的这时我们可以用分类去实现这个功能
1
@interface UITextField (SCPlaceHolder)
2
@property (nonatomic,strong)IBInspectable UIColor *sc_placeHolderColor;
3
@end
4
@implementation UITextField (SCPlaceHolder)
5
- (void)setSc_placeHolderColor:(UIColor *)sc_placeHolderColor {
6
    ((UILabel *)[self valueForKey:@"placeholderLabel"]).textColor = sc_placeHolderColor;
7
}
8
- (UIColor *)sc_placeHolderColor{
9
    return ((UILabel *)[self valueForKey:@"placeholderLabel"]).textColor;
10
}
11
@end