更改UITextField占位符颜色

the*_*ker 74 uitextfield ios

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

xib编辑器中没有选项.

Dog*_*fee 161

来自Docs

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

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

Objective-C的

NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"Some Text" attributes:@{ NSForegroundColorAttributeName : [UIColor redColor] }];
self.myTextField.attributedPlaceholder = str;
Run Code Online (Sandbox Code Playgroud)

迅速

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

斯威夫特4

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

  • 如果您只支持iOS 7及更高版本,这是正确的密钥. (3认同)

iAh*_*med 41

简单而完美的解决方案

_placeholderLabel.textColor
Run Code Online (Sandbox Code Playgroud)

在迅速

myTextField.attributedPlaceholder = 
NSAttributedString(string: "placeholder", attributes:[NSForegroundColorAttributeName : UIColor.redColor()])
Run Code Online (Sandbox Code Playgroud)

Objective-C的

UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =
   [[NSAttributedString alloc]
   initWithString:@"Full Name"
   attributes:@{NSForegroundColorAttributeName:color}];
Run Code Online (Sandbox Code Playgroud)

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

  • _placeholderLabel的警告:某些用户报告App Store拒绝:http://stackoverflow.com/questions/1340224/iphone-uitextfield-change-placeholder-text-color#comment56758204_22017127 (3认同)

Pra*_*inh 12

使用以下代码

[YourtextField setValue:[UIColor colorWithRed:97.0/255.0 green:1.0/255.0 blue:17.0/255.0 alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用此应用程序,您的应用程序将被拒绝,您正在访问私有API.而是使用UITextField的attributedPlaceholder属性. (4认同)
  • 是的,您是对的,这是私人财产。无论如何,以这种方式访问​​属性/变量不是一个好习惯。有一天,Apple可以将该属性的名称更改为其他名称,这将使应用程序崩溃,并且您的代码中将不会收到任何编译警告。 (2认同)

小智 5

首先添加此扩展名

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

textfield.placeHolderTextColor = UIColor.red
Run Code Online (Sandbox Code Playgroud)