您的位置:首页 > 移动开发 > IOS开发

ios textfield 修改 placeholder color 颜色

2015-10-21 10:01 661 查看
UITextField修改placeholder color有很多种方式,但选择哪一种看你自己,有一些方法并不建议,同时希望大家分享没有摘录的方法,tks

方法一(不推荐):

[_textPhone setValue:[UIColor whiteColor]
forKeyPath:@"_placeholderLabel.textColor"];

最直接一句话搞定,使用KVC模式直接设置TestField的私有属性的值。没错,_placeholderLabel是一个私有的属性,使用这种方式虽然简单但并不是很好的做法,如果Apple修改(虽然至今没有修改)了该属性名后,会在之后的运行中遭遇崩溃,而编译器却无法识别。
有人说使用KVC修改私有属性可能提交 app store审核不通过,但也有人说能通过,自己试试吧~

方法二(不推荐):



意思同方法一

方法三:

UIColor *color = [UIColor whiteColor];
_textPhone.attributedPlaceholder = [[NSAttributedString alloc] initWithString:_textPhone.placeholder attributes:@{NSForegroundColorAttributeName: color}];使用UITextField的共有属性attributedPlaceholder,妥妥的,虽然代码略长~

方法四:

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
UIColor *color = [UIColor whiteColor];
self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:@{NSForegroundColorAttributeName: color}];
// 以下注释的方法,在ios7后被放弃
// [[UIColor whiteColor] setFill];
// [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
//

}

创建一个类继承UITextField,并重写该方法,使用该类即可,略麻烦,但如果是公用textField,推荐这种方法,可以添加更多设置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息