Change UITextField's placeholder text color programmatically

∥☆過路亽.° 提交于 2019-11-30 08:43:59

when user does not write any thing in textfield. then put this text as a textfield.text text and change font color.

Just look at this:

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

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

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 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)

We can gain access to place holder label using key path,so that we can change color i.e.:

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

You can set the placeholder text as a NSAttributedString using this property

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

override

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

I had some difficulty implementing color change of placeholder, instead I've found another solution which works perfectly for me.

//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];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!