更改UITextField占位符颜色

 好人___夏洁 发布于 2023-02-04 12:55

如何动态更改占位符颜色UITextField?这始终是相同的系统颜色.

xib编辑器中没有选项.

4 个回答
  • 来自Docs

    @property(非原子,复制)NSAttributedString*attributedPlaceholder

    默认情况下,此属性为零.如果设置,则使用70%灰色和属性字符串的剩余样式信息(文本颜色除外)绘制占位符字符串.为此属性分配新值也会使用相同的字符串数据替换占位符属性的值,尽管没有任何格式设置信息.为此属性指定新值不会影响文本字段的任何其他与样式相关的属性.

    Objective-C的

    NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"Some Text" attributes:@{ NSForegroundColorAttributeName : [UIColor redColor] }];
    self.myTextField.attributedPlaceholder = str;
    

    迅速

    let str = NSAttributedString(string: "Text", attributes: [NSForegroundColorAttributeName:UIColor.redColor()])
    myTextField.attributedPlaceholder = str
    

    斯威夫特4

    let str = NSAttributedString(string: "Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
    myTextField.attributedPlaceholder = str
    

    2023-02-04 12:57 回答
  • 首先添加此扩展名

    extension UITextField{
        @IBInspectable var placeHolderTextColor: UIColor? {
            set {
                let placeholderText = self.placeholder != nil ? self.placeholder! : ""
                attributedPlaceholder = NSAttributedString(string:placeholderText, attributes:[NSForegroundColorAttributeName: newValue!])
            }
            get{
                return self.placeHolderTextColor
            }
        }
    }
    

    然后,您可以通过故事板更改占位符文本颜色,或者只需将其设置为:

    textfield.placeHolderTextColor = UIColor.red
    

    2023-02-04 12:57 回答
  • 简单而完美的解决方案

    _placeholderLabel.textColor
    

    在迅速

    myTextField.attributedPlaceholder = 
    NSAttributedString(string: "placeholder", attributes:[NSForegroundColorAttributeName : UIColor.redColor()])
    

    Objective-C的

    UIColor *color = [UIColor grayColor];
    nameText.attributedPlaceholder =
       [[NSAttributedString alloc]
       initWithString:@"Full Name"
       attributes:@{NSForegroundColorAttributeName:color}];
    

    PS复制了Stackoverflow的3个不同答案.

    2023-02-04 12:57 回答
  • 使用以下代码

    [YourtextField setValue:[UIColor colorWithRed:97.0/255.0 green:1.0/255.0 blue:17.0/255.0 alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];
    

    2023-02-04 12:57 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有