我想改变我在UITextField控件中设置的占位符文本的颜色,使其为黑色。
我更喜欢这样做,而不使用普通文本作为占位符,并且不得不重写所有方法来模仿占位符的行为。
我相信如果我重写这个方法:
- (void)drawPlaceholderInRect:(CGRect)rect
那么我就能做这个了。但是我不确定如何从这个方法中访问实际的占位符对象。
我想改变我在UITextField控件中设置的占位符文本的颜色,使其为黑色。
我更喜欢这样做,而不使用普通文本作为占位符,并且不得不重写所有方法来模仿占位符的行为。
我相信如果我重写这个方法:
- (void)drawPlaceholderInRect:(CGRect)rect
那么我就能做这个了。但是我不确定如何从这个方法中访问实际的占位符对象。
当前回答
Xamarin的。iOS开发者,我从这个文档中找到的 https://developer.xamarin.com/api/type/Foundation.NSAttributedString/
textField.AttributedPlaceholder = new NSAttributedString ("Hello, world",new UIStringAttributes () { ForegroundColor = UIColor.Red });
其他回答
也许你想尝试这种方式,但苹果可能会警告你访问私有ivar:
[self.myTextField setValue:[UIColor darkGrayColor]
forKeyPath:@"_placeholderLabel.textColor"];
请注意 根据Martin Alléus的说法,iOS 7不再适用了。
重写drawPlaceholderInRect:将是正确的方式,但由于API(或文档)中的错误,它不起作用。
该方法永远不会在UITextField上被调用。
参见drawTextInRect on UITextField not called
你可以使用digdog的解决方案。因为我不确定这是否通过了苹果的审查,我选择了一个不同的解决方案:用我自己的标签覆盖文本字段,模仿占位符行为。
这有点乱。 代码看起来像这样(注意,我在TextField的子类中这样做):
@implementation PlaceholderChangingTextField
- (void) changePlaceholderColor:(UIColor*)color
{
// Need to place the overlay placeholder exactly above the original placeholder
UILabel *overlayPlaceholderLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.frame.origin.x + 8, self.frame.origin.y + 4, self.frame.size.width - 16, self.frame.size.height - 8)] autorelease];
overlayPlaceholderLabel.backgroundColor = [UIColor whiteColor];
overlayPlaceholderLabel.opaque = YES;
overlayPlaceholderLabel.text = self.placeholder;
overlayPlaceholderLabel.textColor = color;
overlayPlaceholderLabel.font = self.font;
// Need to add it to the superview, as otherwise we cannot overlay the buildin text label.
[self.superview addSubview:overlayPlaceholderLabel];
self.placeholder = nil;
}
另一个不需要子类化的选项-留空占位符,并将标签放在编辑按钮的顶部。管理标签就像你会管理占位符(清除一旦用户输入任何东西..)
同样在你的故事板中,没有一行代码
我需要保持占位符的对齐,这样亚当的答案对我来说就不够了。
为了解决这个问题,我使用了一个小的变化,我希望也能帮助到你们:
- (void) drawPlaceholderInRect:(CGRect)rect {
//search field placeholder color
UIColor* color = [UIColor whiteColor];
[color setFill];
[self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];
}