改变Textfield的占位文字的颜色

在项目中由于背景是纯黑色, 有个需求是需要将很多Textfield放在视图上, 所以就产生了改变占位文字的颜色

方法一, 利用NSAttributedString属性来改变placeholderLabel

    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:placehodlerArr[indexPath.row] attributes:
                                      @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                        NSFontAttributeName:self.detailTF.font
                                        }];
    
    
    self.detailTF.attributedPlaceholder = attrString;

方法二, 利用kvc来改变占位文字的颜色, 比较方便, 更适合纯代码的TF结构


    // 使用KVC改变TF的占位文字的颜色
        [_detailTF setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];

方法三, 通过重写UITextField的drawPlaceholderInRect:方法修改占位文字颜色

1、自定义一个TextField继承自UITextField

2、重写drawPlaceholderInRect:方法

3、在drawPlaceholderInRect方法中设置placeholder的属性

// 重写此方法
-(void)drawPlaceholderInRect:(CGRect)rect {
    // 计算占位文字的 Size
    CGSize placeholderSize = [self.placeholder sizeWithAttributes:
                              @{NSFontAttributeName : self.font}];

    [self.placeholder drawInRect:CGRectMake(0, (rect.size.height - placeholderSize.height)/2, rect.size.width, rect.size.height) withAttributes:
    @{NSForegroundColorAttributeName : [UIColor blueColor],
                 NSFontAttributeName : self.font}];
}

PS:快该过年了, 回望2016, 收获满满, 加油了, 不懂冯先生.
做一个阳光积极的人
-END-

你可能感兴趣的:(改变Textfield的占位文字的颜色)