我想改变我在UITextField控件中设置的占位符文本的颜色,使其为黑色。
我更喜欢这样做,而不使用普通文本作为占位符,并且不得不重写所有方法来模仿占位符的行为。
我相信如果我重写这个方法:
- (void)drawPlaceholderInRect:(CGRect)rect
那么我就能做这个了。但是我不确定如何从这个方法中访问实际的占位符对象。
我想改变我在UITextField控件中设置的占位符文本的颜色,使其为黑色。
我更喜欢这样做,而不使用普通文本作为占位符,并且不得不重写所有方法来模仿占位符的行为。
我相信如果我重写这个方法:
- (void)drawPlaceholderInRect:(CGRect)rect
那么我就能做这个了。但是我不确定如何从这个方法中访问实际的占位符对象。
当前回答
同样在你的故事板中,没有一行代码
其他回答
你可以重写drawPlaceholderInRect:(CGRect)rect来手动渲染占位符文本:
- (void) drawPlaceholderInRect:(CGRect)rect {
[[UIColor blueColor] setFill];
[[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
}
适用于iOS 6.0 +
[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];
希望能有所帮助。
注意:苹果可能会拒绝(0.01%的机会)你的应用程序,因为我们正在访问私有API。这两年以来,我一直在我的所有项目中使用这个功能,但苹果并没有要求我这么做。
有了这个,我们可以在iOS中改变文本字段占位符文本的颜色
[self.userNameTxt setValue:[UIColor colorWithRed:41.0/255.0 green:91.0/255.0 blue:106.0/255.0 alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];
你可以改变占位符文本颜色的任何颜色,你想通过使用下面的代码。
UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];
对于那些使用Monotouch (Xamarin.iOS)的人,这里是Adam的答案,翻译成c#:
public class MyTextBox : UITextField
{
public override void DrawPlaceholder(RectangleF rect)
{
UIColor.FromWhiteAlpha(0.5f, 1f).SetFill();
new NSString(this.Placeholder).DrawString(rect, Font);
}
}