UITextField placeholder color or font

有时我们在用到 UITextField 的属性的时候,需要做出一些不常规的属性,例如改变placeholder 的字体或颜色啊

方法一、runtime 获取类的成员变量,拿到相应的变量名用KVO 设置

 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形式;  

方法二、利用富文本设置attributedPlaceholder

 textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Placeholder Text"
        attributes:@{
                      NSForegroundColorAttributeName: [UIColor redColor],
                      NSFontAttributeName : [UIFont systemFontOfSize:16]
                    }
 ];

方法三、自定义UITextField 重写drawPlaceholderInRect方法

– textRectForBounds:      //重写来重置文字区域
– drawTextInRect:         //改变绘文字属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了.
– placeholderRectForBounds:  //重写来重置占位符区域
– drawPlaceholderInRect:  //重写改变绘制占位符属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了
– borderRectForBounds:  //重写来重置边缘区域
– editingRectForBounds:  //重写来重置编辑区域
– clearButtonRectForBounds:  //重写来重置clearButton位置,改变size可能导致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;
}

总的来说,推荐方法二利用富文本设置attributedPlaceholder,简单明了,不宜出错。

你可能感兴趣的:(UITextField placeholder color or font)