IOS_改变UITextField placeHolder颜色、字体

来源:互联网 发布:天刀捏脸数据男禁欲 编辑:程序博客网 时间:2024/05/23 01:57

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

[textField setValue:[UIColorredColor] forKeyPath:@"_placeholderLabel.textColor"];

[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

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

UITextField*textField=[[UITextFieldalloc] initWithFrame:CGRectMake(0,0,200,200)];
NSString*holderText=@"标哥的技术博客";
NSMutableAttributedString*placeholder=[[NSMutableAttributedStringalloc] initWithString:holderText];
[placeholder addAttribute:NSForegroundColorAttributeName
                  value:[UIColorredColor]
                  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说明
其实_placeholderLabel就是UITextFieldLabel类型,这是在有placeholder的情况下打印出来的,但是为什么知道内部叫\ _placeholderLabel呢?根据苹果的命名规范,猜测出来的,然后测试能否获取到。这不算私有API,这是通过KVC获取的,虽然苹果并不希望我们这么做,但是可以正常上架(笔者在很多个App里使用过)

说明

  • iOS6.0之后,有attributedPlaceholder属性,因此可以直接通过它设置。
  • 在iOS6.0之前,可以通过KVC来设置_placeholderLabel的属性值。


0 0
原创粉丝点击