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

Ed *_*dez 20 uitextfield ios

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

iPhone UITextField - 更改占位符文本颜色

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

For*_*est 36

来自iOS 6,

没有任何子类,人们可以通过几行代码完成此操作,如下所示:

UIColor *color = [UIColor blackColor];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];
Run Code Online (Sandbox Code Playgroud)


ABS*_*ABS 22

有多种方法可以实现这一目标.

使用Interface Builder或Storyboard

  • 选择要更改占位符颜色的文本字段
  • 转到Xcode右上角的Identity检查器菜单
  • 以这种方式添加键值对

关键路径 =_placeholderLabel.textColor

单击"类型"并选择"颜色"属性.

然后选择值中的颜色.

在此输入图像描述

使用代码设置占位符颜色:

过程1:

[textField setValue:[UIColor blueColor] forKeyPath:@"_placeholderLabel.textColor"];
Run Code Online (Sandbox Code Playgroud)

过程2:

覆盖drawPlaceholderInRect:(CGRect)rect方法

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


Ed *_*dez 15

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

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

在这个例子中,我们创建了一个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];

    }
}
Run Code Online (Sandbox Code Playgroud)

这种方法的优点在于它维护了placeHolder字符串的当前UITextField属性,因此允许您在IB中设置大部分内容.此外,它比每次需要绘制时更有效率.它还允许您在placeHolder文本上更改所需的任何其他属性,同时保留其余属性.

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