< 返回首页

标哥的笔记,是记录在日常学习技术和日常开发中那些年遇到过的坑!本站为新站,原"标哥的技术博客"中的文章会慢慢移到本站,欢迎收藏本站!
在使用本站过程中,有任何建议请联系标哥! 另,承接App开发、网站开发和微信小程序开发!欢迎联系我们


ios修改textField的placeholder字体颜色

 作者:标哥    发布日期:2017-01-12 22:08    阅读量:1060次
 

使用到UITextField时,通常都需要到其placeholder属性设置,而UI往往给我们设计的效果图中,placeholder跟系统的颜色或者字体大小不一样。

那么我们如何修改UITextField的属性placeholder的颜色和字体大小呢?

如何修改

6.0之前,可以通过这种方式

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

textField.placeholder = @"username is in here!";  
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];  
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

在iOS6.0之后提供的attributedPlaceholder属性:

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
NSString *holderText = @"标哥的技术博客";
NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:holderText];
[placeholder addAttribute:NSForegroundColorAttributeName
                  value:[UIColor redColor]
                  range:NSMakeRange(0, holderText.length)];
[placeholder addAttribute:NSFontAttributeName
                  value:[UIFont boldSystemFontOfSize:16]
                  range:NSMakeRange(0, holderText.length)];
textField.attributedPlaceholder = placeholder;
[cell.contentView addSubview:textField];

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

重点说明

_placeholderLabel这个变量是怎么知道的呢?其实我们是通过UI调试时,通过遍历打印看到的!

(lldb) po [textField valueForKey:@"_placeholderLabel"]
<UITextFieldLabel: 0x13fe835f0; frame = (0 0; 0 0); text = '标哥的技术博客'; opaque = NO; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x13fe855f0>>

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

说明

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

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


承接:ThinkPHP项目开发、网站项目开发、微信项目开发、微信小程序项目开发、App开发,欢迎联系标哥QQ632840804