更改UITextField的占位符字体

67

我正在使用以下代码更改占位符文本的颜色,但是当我尝试添加NSFontAttribute时,我会遇到编译器错误"too many arguments to method call, expect 2 have 3"

 UIColor *color = [UIColor blackColor];
        _nameField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Your Name" attributes:@{NSForegroundColorAttributeName: color},@{NSFontAttributeName:@"Roboto-Bold"}]; 

这样做很好:

 UIColor *color = [UIColor blackColor];
        _nameField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Your Name" attributes:@{NSForegroundColorAttributeName: color}]; 
14个回答

153

Objective-C:

UIColor *color = [UIColor blackColor];    
someUITextField.attributedPlaceholder =
  [[NSAttributedString alloc] initWithString:@"Placeholder Text"
    attributes:@{
       NSForegroundColorAttributeName: color,
       NSFontAttributeName : [UIFont fontWithName:@"Roboto-Bold" size:17.0]
    }
  ];

(在字面意义上的dictionary键值对之间没有括号。)

Swift:

let attributes = [
    NSForegroundColorAttributeName: UIColor.blackColor(),
    NSFontAttributeName : UIFont(name: "Roboto-Bold", size: 17)! // Note the !
]

someUITextField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes:attributes)

4
NSFontAttributeName 需要一个 UIFont 对象作为参数,而不是一个字符串。你需要使用类似 NSFontAttributeName : [UIFont fontWithName:@"Roboto-Bold" size:17.0] 的方式来传递参数。 - jmstone617
3
这改变了颜色,但字体没有变。 - kraftydevil
是的,在iOS7中字体没有改变。 - xi.lin
当我使用这段代码改变字体大小时,文本框中占位符的位置会向下移动,导致垂直居中不再准确。有什么办法可以增加占位符文本的字体大小,同时保持其在文本框内垂直居中吗? - RanLearns

30

更新至 Swift 4.x:

textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [
    .foregroundColor: UIColor.lightGray,
    .font: UIFont.boldSystemFont(ofSize: 14.0)
])

它在Xcode 8.3.2和Swift 3上运行良好,只需要使用as [String: Any]进行属性转换即可。 - Claus

12

为了方便迅速的人:

someTextField.attributedPlaceholder = NSAttributedString(string: "someString", 
attributes:[NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: PlaceHolderFont])

7
您需要子类化UITextField,并重写以下方法:
- (void)drawPlaceholderInRect:(CGRect)rect;

以下是实现代码:
- (void)drawPlaceholderInRect:(CGRect)rect {
     NSDictionary *attributes = @{
                             NSForegroundColorAttributeName : [UIColor lightGrayColor],
                             NSFontAttributeName : [UIFont italicSystemFontOfSize:self.font.pointSize]
                             };
    // center vertically
    CGSize textSize = [self.placeholder sizeWithAttributes:attributes];
    CGFloat hdif = rect.size.height - textSize.height;
    hdif = MAX(0, hdif);
    rect.origin.y += ceil(hdif/2.0);
    [[self placeholder] drawInRect:rect withAttributes:attributes];
}

For more you can find click here


5

感谢 @ddevaz 的回答。

UITextField 子类解决方案

上面的回答对于 UITextField 来说完美适用。但是当我使用 UITextField 子类并尝试在其中执行此方法时,它就不起作用了。

我发现只有当你子类化 UITextField 时才有另一种解决方案。在您的 UITextField 子类中重写以下方法即可完成工作。

- (void) drawPlaceholderInRect:(CGRect)rect {
    NSDictionary *attrDictionary = @{
                                     NSForegroundColorAttributeName: [UIColor lightGrayColor],
                                     NSFontAttributeName : [UIFont fontWithName:@"Menlo" size:17.0]
                                     };

    [[self placeholder] drawInRect:rect withAttributes:attrDictionary];
}

4

适用于Swift 4的工作版本

let attributes = [NSAttributedStringKey.foregroundColor: UIColor.black,
                      .font : UIFont.systemFont(ofSize: 14, weight: .regular)]

someTextfield.attributedPlaceholder = NSAttributedString(string: "Placeholder text", attributes:attributes)

3

Swift 4更新说明

let attributes = [
    NSAttributedStringKey.foregroundColor: .black,
    NSAttributedStringKey.font : UIFont(name: "Your font name", size: 14)!
]

someTextfield.attributedPlaceholder = NSAttributedString(string: "Placeholder text", attributes:attributes)

3

更新至Swift 4.2版本以上

let attributes = [NSAttributedString.Key.foregroundColor: UIColor.black,
                  .font: UIFont.systemFont(ofSize: 14)]

searchTextField.attributedPlaceholder = NSAttributedString(string: "Placeholder text",
                                                           attributes: attributes)

更多属性键的参考 - NSAttributedString.Key


1
如果您想支持iOS 6及之前版本,则需按照以下方式操作:
UIColor *placeholderColor = [UIColor lightTextColor];
UIFont *placeholderFont = [UIFont systemFontOfSize:[UIFont systemFontSize]];

if ([textField respondsToSelector:@selector(attributedPlaceholder)]) {
#ifdef __IPHONE_6_0
    textField.attributedPlaceholder = [[NSAttributedString alloc]
        initWithString:textField.placeholder attributes: // NOTE: textField.placeholder can't be nil
              @{ NSForegroundColorAttributeName : placeholderColor,
                 NSFontAttributeName : placeholderFont }];
#endif
} else { // for pre-iOS6
    [textField setValue:placeholderColor forKeyPath:@"_placeholderLabel.textColor"];
    [textField setValue:placeholderFont forKeyPath:@"_placeholderLabel.font"];
}

0

Swift 4:使用UITextField子类更改占位符颜色

override func drawPlaceholder(in rect: CGRect) {

        let color = UIColor(red: 210/255, green: 210/255, blue: 210/255, alpha: 1.0)

        if (placeholder?.responds(to: #selector(NSString.draw(in:withAttributes:))))! {

            let fontS = UIFont.systemFont(ofSize: 12)

            let attributes = [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: fontS] as [NSAttributedStringKey : Any]

            let boundingRect: CGRect = placeholder!.boundingRect(with: rect.size, options: [], attributes: attributes, context: nil)

            placeholder?.draw(at: CGPoint(x: 0, y: (rect.size.height / 2) - boundingRect.size.height / 2), withAttributes: attributes)
        }

 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接