如何设置UITextField的占位符文本的颜色,同时保留其现有属性?

我已经看到一些答案,显示如何通过重写drawPlaceholderInRect:方法来更改UITextField的placeHolder文本颜色:

iPhone的UITextField – 改变占位符的文字颜色

但是不能保持现有的属性,如alignment,字体等…有什么更好的方法来解决这个问题?

从iOS 6开始,

没有任何子类化,可以用几行代码来完成这个工作:

UIColor *color = [UIColor blackColor]; textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}]; 

有多种方法来实现这一点。

使用Interface Builder或Storyboard

  • select您要为其更改占位符颜色的文本框
  • 转到Xcode右上angular的“身份检查器”菜单
  • 以这种方式添加键值对

关键path = _placeholderLabel.textColor

单击types并select颜色属性。

然后select颜色值。

在这里输入图像说明

使用代码设置占位符颜色

过程1:

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

过程2:

覆盖drawPlaceholderInRect:(CGRect)rect方法

 - (void) drawPlaceholderInRect:(CGRect)rect { [[UIColor blueColor] setFill]; [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:14]]; } 

现在确实有更好的方法来处理这个问题。 这将适用于iOS 6和7。

(注意这个例子,我在AwakeFromNib中创build了这个代码,因为它一旦设置就不会改变颜色,但是如果你不使用XIB,你将不得不改变放置这个代码的位置,比如在drawPlaceholderInRect中)

在这个例子中,我们创build了UITextField的子类,重写了awakeFromNib,然后将placeHolder文本的颜色设置为红色:

 - (void)awakeFromNib { if ([self.attributedPlaceholder length]) { // Extract attributes NSDictionary * attributes = (NSMutableDictionary *)[ (NSAttributedString *)self.attributedPlaceholder attributesAtIndex:0 effectiveRange:NULL]; NSMutableDictionary * newAttributes = [[NSMutableDictionary alloc] initWithDictionary:attributes]; [newAttributes setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName]; // Set new text with extracted attributes self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:[self.attributedPlaceholder string] attributes:newAttributes]; } } 

这种方法的好处在于,它维护了placeHolderstring的当前UITextField属性,因此可以在IB中为您设置的大部分内容工作。 另外,它比每次需要绘制都要高效得多。 它还允许您在placeHolder文本中更改任何其他属性,同时保留其余的属性。

如上所述,如果不使用XIB,那么您需要在其他时间调用它。 如果你把这段代码放在drawPlaceholderInRect:方法中,那么确保你在它的结尾调用了[super drawPlaceholderInRect:]。

自定义UITextField的占位符的安全方法是UITextField并覆盖placeholderRectForBounds: ,Apple不会打扰你。 但是,如果您想冒险,可以尝试这种方式:

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

来源 。