美文网首页
修改UITextField的placeholder大小颜色并垂直

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

作者: 何以_aaa | 来源:发表于2017-04-24 14:44 被阅读60次

    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}];```

    相关文章

      网友评论

          本文标题:修改UITextField的placeholder大小颜色并垂直

          本文链接:https://www.haomeiwen.com/subject/xbhpzttx.html