我有一个带占位符的UITextField
。当用户想要提交表单并且他/她没有在文本字段中输入任何内容时,我希望占位符的文本颜色变为红色。以下是我的问题:
我知道我可以覆盖drawPlaceholderInRect:
的子类中的方法UITextField
。但是,如果我这样做,文本将始终是红色的,正如我之前写的那样,我希望它根据用户定义的操作变为红色。
我能想到的唯一解决方案是为我的UITextField
(占位符的文本)使用“默认”文本,只要用户没有键入任何内容并将其显示在我需要时红了。换句话说,我只是嘲笑占位符的行为。但当然,这不是很优雅。
有什么想法吗?
答案 0 :(得分:48)
看看这个:
Digdog Dig - Change UITextField’s placeholder color without subclassing it
[self.MyTextField setValue:[UIColor darkGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
答案 1 :(得分:24)
您可以使用以下代码将占位符文本颜色更改为任何颜色。试试吧。
UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];
答案 2 :(得分:12)
喜欢来自verklixt的回答,但没有访问私有API并使用UIAppearance
:
[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor darkGrayColor]];
(在5.0到7.1测试)
答案 3 :(得分:5)
我们可以使用关键路径访问占位符标签,以便我们可以改变颜色,即:
[self.textField setValue:[UIColor **"your color"**]
forKeyPath:@"_placeholderLabel.textColor"];
答案 4 :(得分:5)
您可以使用this property
将占位符文本设置为NSAttributedStringNSAttributedString *coloredPlaceholder = [[NSAttributedString alloc] initWithString:@"I am a placeholder string" attributes:@{NSForegroundColorAttributeName: [UIColor redColor]}];
[self.textField setAttributedPlaceholder:coloredPlaceholder];
答案 5 :(得分:4)
倍率
-(void) drawPlaceholderInRect:(CGRect)rect {
[[UIColor darkGrayColor] setFill];
[[self placeholder] drawInRect:rect withFont:[UIFont fontWithName:@"Helvetica-Oblique" size:15.0]];
}
答案 6 :(得分:2)
当用户没有在textfield中写任何东西时。然后将此文本作为textfield.text文本并更改字体颜色。
答案 7 :(得分:0)
我在实施占位符的颜色变化时遇到了一些困难,相反,我找到了另一种适合我的解决方案。
//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];
}