设置UITextField的placeholder的颜色

前言

设置UITextField的placeholder的颜色代码片段:

textField.placeholder = @"username is in here!";

 [textFieldsetValue:[UIColor redColor]forKeyPath:@"_placeholderLabel.textColor"]; 

 [textFieldsetValue:[UIFontboldSystemFontOfSize:16]forKeyPath:@"_placeholderLabel.font"];

或者直接在iOS6.0之后提供的attributedPlaceholder属性:

UITextField*textField = [[UITextFieldalloc]initWithFrame:CGRectMake(0,0,200,200)];NSString*holderText =@"标哥的技术博客";

NSMutableAttributedString*placeholder = [[NSMutableAttributedStringalloc]initWithString:holderText];[placeholderaddAttribute:NSForegroundColorAttributeNamevalue:[UIColorredColor]                  range:NSMakeRange(0, holderText.length)];[placeholderaddAttribute:NSFontAttributeNamevalue:[UIFontboldSystemFontOfSize:16]                  range:NSMakeRange(0, holderText.length)];textField.attributedPlaceholder = placeholder;[cell.contentViewaddSubview:textField];

与上面那段代码是一样的效果。

_placeholderLabel说明

(lldb) po [textFieldvalueForKey:@"_placeholderLabel"]>

其实_placeholderLabel就是UITextFieldLabel类型,这是在有placeholder的情况下打印出来的,但是为什么知道内部叫\ _placeholderLabel呢?根据苹果的命名规范,猜测出来的,然后测试能否获取到。这不算私有API,这是通过KVC获取的,虽然苹果并不希望我们这么做,但是可以正常上架(笔者在很多个App里使用过)。

说明

iOS6.0之后,有attributedPlaceholder属性,因此可以直接通过它设置。

在iOS6.0之前,可以通过KVC来设置_placeholderLabel的属性值。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容