Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change UITextField's placeholder text color programmatically

I have a UITextField with a placeholder. When the user wants to submit the form and he/she hasn't typed anything in the textfield, I would like the placeholder's text color become red. Here are my questions:

  • Would that go against Apple's User interface guidelines? I don't want my app to be rejected because of such small detail.
  • How I would do it?

I know I can override the method drawPlaceholderInRect: in a subclass of UITextField. But if I did this, the text would be always red and as I wrote before, I would like it to become red depending on a user defined action.

The only solution I can think of is to use a "default" text for my UITextField (the placeholder's text), display it in light grey as long as the user hasn't typed anything and display it in red when I need it. In other words, I would just mock the placeholder's behavior. But of course, this is not very elegant.

Any ideas?

like image 532
strave Avatar asked Sep 07 '11 09:09

strave


3 Answers

Just look at this:

Digdog Dig - Change UITextField’s placeholder color without subclassing it

[self.MyTextField setValue:[UIColor darkGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
like image 71
verklixt Avatar answered Nov 13 '22 22:11

verklixt


You can Change the Placeholder textcolor to any color by using the below code. Just try this.

UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];
like image 26
Atanu Mondal Avatar answered Nov 13 '22 21:11

Atanu Mondal


like the answer from verklixt but without accessing private api and using UIAppearance:

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

(tested on 5.0 through 7.1)

like image 12
glasz Avatar answered Nov 13 '22 20:11

glasz