修改UITextField的placeholder大小颜色并垂直居中

1.修改UITextField的placeholder的大小颜色有2种方法

1.1 KVC
TextField.placeholder = rightText;
[TextField setValue:KColorFontGray forKeyPath:@"_placeholderLabel.textColor"];
[TextField setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];```
#####1.2 attributedPlaceholder(iOS6以后)

NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:rightText
attributes:@{NSForegroundColorAttributeName:KColorFontGray,
NSFontAttributeName:[UIFont boldSystemFontOfSize:14.0f]}];
rightTextField.attributedPlaceholder = placeholder;```
但是这样做存在一个问题,设置的字号过小之后,placeholder会不再垂直居中,如下图效果:

问题.png

2.解决上述垂直居中问题

在attributes中再添加一组属性,即可解决

NSMutableParagraphStyle *style = [rightTextField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
    
style.minimumLineHeight = rightTextField.font.lineHeight - (rightTextField.font.lineHeight - [UIFont systemFontOfSize:14.0f].lineHeight) / 2.0;
    
TextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:rightText
                                                                           attributes:@{NSForegroundColorAttributeName:KColorFontGray,
                                                                                        NSFontAttributeName : [UIFont systemFontOfSize:14.0f],
                                                                                        NSParagraphStyleAttributeName : style}];```
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容