Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the color of the place holder text for a UITextField while preserving its existing properties?

I have seen some answers that show how to change the placeHolder text color for UITextField by overriding the drawPlaceholderInRect: method such as this one:

iPhone UITextField - Change placeholder text color

but that does not maintain the existing attributes such as alignment, font, etc...what is a better way to solve this?

like image 361
Ed Fernandez Avatar asked Sep 03 '13 05:09

Ed Fernandez


People also ask

How do I change the color of a textfield in Swift?

Select the text field -> click "identity inspector" icon -> click on Plus button "user Defined runtime attributes" -> add this text "_placeholderLabel. textColor" in "key path" field -> choose the "Type" "color" and set the value color. Save this answer. Show activity on this post.

How do you add a place holder in text view?

First set the UITextView to contain the placeholder text and set it to a light gray color to mimic the look of a UITextField 's placeholder text. Either do so in the viewDidLoad or upon the text view's creation.


2 Answers

From iOS 6,

Without any subclassing, one can accomplish this with a couple lines of code like so:

UIColor *color = [UIColor blackColor];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];
like image 54
Forrest Avatar answered Oct 25 '22 14:10

Forrest


There are multiple ways to achieve this.

Using Interface Builder or Storyboard

  • Select the Textfield for which you want to change placeholder color
  • go to the Identity inspector menu on Top right of Xcode
  • Add the key value pair this way

Key path = _placeholderLabel.textColor

Click the Type and chose Color attribute .

Then select the color in value.

enter image description here

Set The placeholder color using code :

Process 1:

[textField setValue:[UIColor blueColor] forKeyPath:@"_placeholderLabel.textColor"];

Process 2 :

Override drawPlaceholderInRect:(CGRect)rect method

- (void) drawPlaceholderInRect:(CGRect)rect {
    [[UIColor blueColor] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:14]];
}
like image 22
ABS Avatar answered Oct 25 '22 14:10

ABS