以编程方式更改UITextField的占位符文本颜色

我有一个占位符的UITextField 。 当用户想要提交表单并且他/她没有在文本框中input任何内容时,我想让占位符的文字颜色变成红色。 这是我的问题:

  • 这是否会违反苹果的用户界面指南? 我不希望我的应用因为这么小的细节而被拒绝。
  • 我该怎么做呢?

我知道我可以覆盖方法drawPlaceholderInRect:UITextField的子类。 但是,如果我这样做,文本将永远是红色的,正如我以前写的,我希望它成为红色取决于用户定义的行动。

我能想到的唯一解决scheme是为我的UITextField (占位符的文本)使用“默认”文本,只要用户没有input任何内容,并在我需要时显示为红色,就以浅灰色显示。 换句话说,我只是嘲笑占位符的行为。 但是,当然,这不是很优雅。

有任何想法吗?

当用户不写任何东西在文本字段。 然后将该文本作为textfield.text文本并更改字体颜色。

只要看看这个:

Digdog Dig – 更改UITextField的占位符颜色,而不用创build子类

 [self.MyTextField setValue:[UIColor darkGrayColor] forKeyPath:@"_placeholderLabel.textColor"]; 

您可以使用下面的代码将占位符textcolor更改为任何颜色。 试试这个

 UIColor *color = [UIColor lightTextColor]; YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}]; 

像verklixt的答案,但没有访问私人API,并使用UIAppearance

 [[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor darkGrayColor]]; 

(在5.0到7.1上testing)

我们可以使用关键path访问占位符标签,以便我们可以改变颜色,即:

 [self.textField setValue:[UIColor **"your color"**] forKeyPath:@"_placeholderLabel.textColor"]; 

您可以使用此属性将占位符文本设置为NSAttributedString

 NSAttributedString *coloredPlaceholder = [[NSAttributedString alloc] initWithString:@"I am a placeholder string" attributes:@{NSForegroundColorAttributeName: [UIColor redColor]}]; [self.textField setAttributedPlaceholder:coloredPlaceholder]; 

覆盖

 -(void) drawPlaceholderInRect:(CGRect)rect { [[UIColor darkGrayColor] setFill]; [[self placeholder] drawInRect:rect withFont:[UIFont fontWithName:@"Helvetica-Oblique" size:15.0]]; } 

我在实现占位符的颜色变化时遇到了一些困难,相反,我find了另一个完全适合我的解决scheme。

 //On button action change color to red -(void)btnAction { // authentication for missing textfields if ([textField_firstName.text isEqualToString:@""]) { textField_firstName.textColor=[UIColor redColor]; textField_firstName.text=@"Enter First Name"; } } // in the delegate method of UITextField change the following - (void)textFieldDidBeginEditing:(UITextField *)textField { //match the following string with above string and change the string to empty string on textfield click if ([textField_firstName.text isEqualToString:@"Enter First Name" ]) { textField_firstName.text=@""; } //change back to the text color you use textField_firstName.textColor=[UIColor blackColor]; }