582

我想更改我在UITextField控件中设置的占位符文本的颜色,使其变为黑色。

我宁愿这样做而不使用普通文本作为占位符,并且不必重写所有方法来模仿占位符的行为。

我相信如果我重写这个方法:

- (void)drawPlaceholderInRect:(CGRect)rect

那么我应该能够做到这一点。但我不确定如何从这个方法中访问实际的占位符对象。

4

32 回答 32

817

由于在 iOS 6 中的 UIViews 中引入了属性字符串,因此可以为占位符文本分配颜色,如下所示:

if ([textField respondsToSelector:@selector(setAttributedPlaceholder:)]) {
  UIColor *color = [UIColor blackColor];
  textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];
} else {
  NSLog(@"Cannot set placeholder text's color, because deployment target is earlier than iOS 6.0");
  // TODO: Add fall-back code to set placeholder color.
}
于 2012-12-04T03:08:32.933 回答
239

简单无痛,对某些人来说可能是一个简单的选择。

_placeholderLabel.textColor

不建议用于生产,Apple 可能会拒绝您的提交。

于 2014-02-25T14:28:30.490 回答
195

您可以这样覆盖drawPlaceholderInRect:(CGRect)rect以手动呈现占位符文本:

- (void) drawPlaceholderInRect:(CGRect)rect {
    [[UIColor blueColor] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
}
于 2010-08-03T11:35:41.457 回答
175

您可以使用以下代码将占位符文本颜色更改为您想要的任何颜色。

UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];
于 2013-11-08T06:18:30.913 回答
172

这适用于 Swift <3.0:

myTextField.attributedPlaceholder = 
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])

在 iOS 8.2 和 iOS 8.3 beta 4 中测试。

斯威夫特 3:

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.red])

斯威夫特 4:

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])

斯威夫特 4.2:

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
于 2015-01-06T11:50:51.923 回答
158

也许您想尝试这种方式,但 Apple 可能会警告您访问私有 ivar:

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

注意
根据 Martin Alléus 的说法,这不再适用于 iOS 7。

于 2010-01-04T07:53:52.087 回答
84

Swift 3.0 + 故事板

为了更改情节提要中的占位符颜色,请使用下一个代码创建扩展。(请随时更新此代码,如果您认为,它可以更清晰,更安全)。

extension UITextField {
    @IBInspectable var placeholderColor: UIColor {
        get {
            guard let currentAttributedPlaceholderColor = attributedPlaceholder?.attribute(NSForegroundColorAttributeName, at: 0, effectiveRange: nil) as? UIColor else { return UIColor.clear }
            return currentAttributedPlaceholderColor
        }
        set {
            guard let currentAttributedString = attributedPlaceholder else { return }
            let attributes = [NSForegroundColorAttributeName : newValue]

            attributedPlaceholder = NSAttributedString(string: currentAttributedString.string, attributes: attributes)
        }
    }
}

在此处输入图像描述

斯威夫特 4 版本

extension UITextField {
    @IBInspectable var placeholderColor: UIColor {
        get {
            return attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .clear
        }
        set {
            guard let attributedPlaceholder = attributedPlaceholder else { return }
            let attributes: [NSAttributedStringKey: UIColor] = [.foregroundColor: newValue]
            self.attributedPlaceholder = NSAttributedString(string: attributedPlaceholder.string, attributes: attributes)
        }
    }
}

斯威夫特 5 版本

extension UITextField {
    @IBInspectable var placeholderColor: UIColor {
        get {
            return attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .clear
        }
        set {
            guard let attributedPlaceholder = attributedPlaceholder else { return }
            let attributes: [NSAttributedString.Key: UIColor] = [.foregroundColor: newValue]
            self.attributedPlaceholder = NSAttributedString(string: attributedPlaceholder.string, attributes: attributes)
        }
    }
}
于 2017-05-21T12:05:16.787 回答
77

在斯威夫特:

if let placeholder = yourTextField.placeholder {
    yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder, 
        attributes: [NSForegroundColorAttributeName: UIColor.blackColor()])
}

在 Swift 4.0 中:

if let placeholder = yourTextField.placeholder {
    yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder, 
        attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
}
于 2014-12-11T16:22:48.530 回答
43

以下仅适用于 iOS6+(如 Alexander W 的评论所示):

UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =
   [[NSAttributedString alloc]
       initWithString:@"Full Name"
       attributes:@{NSForegroundColorAttributeName:color}];
于 2014-05-19T06:33:28.037 回答
36

我已经面临这个问题。在我的情况下,下面的代码是正确的。

目标 C

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

对于 Swift 4.X

tf_mobile.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")

对于 iOS 13 Swift 代码

tf_mobile.attributedPlaceholder = NSAttributedString(string:"PlaceHolder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])

您还可以将以下代码用于iOS 13

let iVar = class_getInstanceVariable(UITextField.self, "_placeholderLabel")!
let placeholderLabel = object_getIvar(tf_mobile, iVar) as! UILabel
placeholderLabel.textColor = .red

希望,这可以帮助你。

于 2015-06-20T13:20:14.970 回答
32

有了这个,我们可以在 iOS 中改变 textfield 的占位符文本的颜色

[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"];
于 2016-02-12T07:30:44.607 回答
24

在 Swift 3.X 中

textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes:[NSForegroundColorAttributeName: UIColor.black])

迅速 5

textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor : UIColor.black])
于 2018-01-01T06:25:23.057 回答
22

你为什么不直接使用UIAppearance方法:

[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor whateverColorYouNeed]];
于 2013-12-19T13:08:53.787 回答
18

同样在您的故事板中,无需单行代码

在此处输入图像描述

于 2016-02-05T10:00:44.527 回答
12

对于 iOS 6.0 +

[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];

希望能帮助到你。

注意: 当我们访问私有 API 时,Apple 可能会拒绝(0.01% 的机会)您的应用程序。两年以来,我在所有项目中都使用它,但 Apple 并没有要求这样做。

于 2014-12-30T06:48:33.897 回答
10

对于 Xamarin.iOS 开发人员,我从这个文档 https://developer.xamarin.com/api/type/Foundation.NSAttributedString/中找到了它

textField.AttributedPlaceholder = new NSAttributedString ("Hello, world",new UIStringAttributes () { ForegroundColor =  UIColor.Red });
于 2016-12-07T11:59:25.387 回答
9

斯威夫特版本。可能它会帮助某人。

class TextField: UITextField {
   override var placeholder: String? {
        didSet {
            let placeholderString = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
            self.attributedPlaceholder = placeholderString
        }
    }
}
于 2016-08-29T10:05:15.970 回答
8

iOS 6 及更高版本attributedPlaceholder提供UITextField. iOS 3.2 及更高版本setAttributes:range:提供NSMutableAttributedString.

您可以执行以下操作:

NSMutableAttributedString *ms = [[NSMutableAttributedString alloc] initWithString:self.yourInput.placeholder];
UIFont *placeholderFont = self.yourInput.font;
NSRange fullRange = NSMakeRange(0, ms.length);
NSDictionary *newProps = @{NSForegroundColorAttributeName:[UIColor yourColor], NSFontAttributeName:placeholderFont};
[ms setAttributes:newProps range:fullRange];
self.yourInput.attributedPlaceholder = ms;
于 2013-10-02T01:21:02.900 回答
7

此解决方案适用于 Swift 4.1

    textName.attributedPlaceholder = NSAttributedString(string: textName.placeholder!, attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])
于 2018-10-10T09:54:48.337 回答
6

在 iOS7 中处理垂直和水平对齐以及占位符的颜色。drawInRect 和 drawAtPoint 不再使用当前上下文填充颜色。

https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/CustomTextProcessing/CustomTextProcessing.html

对象-C

@interface CustomPlaceHolderTextColorTextField : UITextField

@end


@implementation CustomPlaceHolderTextColorTextField : UITextField


-(void) drawPlaceholderInRect:(CGRect)rect  {
    if (self.placeholder) {
        // color of placeholder text
        UIColor *placeHolderTextColor = [UIColor redColor];

        CGSize drawSize = [self.placeholder sizeWithAttributes:[NSDictionary dictionaryWithObject:self.font forKey:NSFontAttributeName]];
        CGRect drawRect = rect;

        // verticially align text
        drawRect.origin.y = (rect.size.height - drawSize.height) * 0.5;

        // set alignment
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.alignment = self.textAlignment;

        // dictionary of attributes, font, paragraphstyle, and color
        NSDictionary *drawAttributes = @{NSFontAttributeName: self.font,
                                     NSParagraphStyleAttributeName : paragraphStyle,
                                     NSForegroundColorAttributeName : placeHolderTextColor};


        // draw
        [self.placeholder drawInRect:drawRect withAttributes:drawAttributes];
    }
}

@end
于 2013-11-02T15:22:57.353 回答
6

类别 FTW。可以优化以检查有效的颜色变化。


#import <UIKit/UIKit.h>

@interface UITextField (OPConvenience)

@property (strong, nonatomic) UIColor* placeholderColor;

@end

#import "UITextField+OPConvenience.h"

@implementation UITextField (OPConvenience)

- (void) setPlaceholderColor: (UIColor*) color {
    if (color) {
        NSMutableAttributedString* attrString = [self.attributedPlaceholder mutableCopy];
        [attrString setAttributes: @{NSForegroundColorAttributeName: color} range: NSMakeRange(0,  attrString.length)];
        self.attributedPlaceholder =  attrString;
    }
}

- (UIColor*) placeholderColor {
    return [self.attributedPlaceholder attribute: NSForegroundColorAttributeName atIndex: 0 effectiveRange: NULL];
}

@end
于 2014-05-27T20:35:19.467 回答
6

带有警告的 Swift 5。

let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.someColor ]
let placeHolderString = NSAttributedString(string: "DON'T_DELETE", attributes: attributes)
txtField.attributedPlaceholder = placeHolderString

需要注意的是,您必须在“DON'T_DELETE”所在的位置输入一个非空String值,即使该字符串是在其他地方的代码中设置的。可能会为您节省五分钟的时间。

于 2019-10-31T02:00:36.850 回答
4

覆盖drawPlaceholderInRect:将是正确的方法,但由于 API(或文档)中的错误,它不起作用。

该方法永远不会在UITextField.

另请参阅未调用 UITextField 上的 drawTextInRect

您可能会使用 digdog 的解决方案。由于我不确定这是否能通过 Apple 的审核,所以我选择了一个不同的解决方案:用我自己的标签覆盖文本字段,该标签模仿占位符的行为。

不过这有点乱。代码如下所示(注意我在 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;
}
于 2010-04-06T00:03:32.370 回答
3

我是 xcode 的新手,我找到了一种达到相同效果的方法。

我用所需格式放置了一个 uilabel 代替占位符并将其隐藏在

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    switch (textField.tag)
    {
        case 0:
            lblUserName.hidden=YES;
            break;

        case 1:
            lblPassword.hidden=YES;
            break;
 
        default:
            break;
    }
}

我同意这是一种解决方法,而不是真正的解决方案,但效果与此链接相同

注意:仍然适用于 iOS 7 :|

于 2012-05-23T09:14:32.560 回答
2

对于那些使用 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);
    }
}
于 2013-09-18T17:15:15.347 回答
2

对于 iOS7 和更少,我能做的最好的事情是:

- (CGRect)placeholderRectForBounds:(CGRect)bounds {
  return [self textRectForBounds:bounds];
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
  return [self textRectForBounds:bounds];
}

- (CGRect)textRectForBounds:(CGRect)bounds {
  CGRect rect = CGRectInset(bounds, 0, 6); //TODO: can be improved by comparing font size versus bounds.size.height
  return rect;
}

- (void)drawPlaceholderInRect:(CGRect)rect {
  UIColor *color =RGBColor(65, 65, 65);
  if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
    [self.placeholder drawInRect:rect withAttributes:@{NSFontAttributeName:self.font, UITextAttributeTextColor:color}];
  } else {
    [color setFill];
    [self.placeholder drawInRect:rect withFont:self.font];
  }
}
于 2013-09-25T07:02:26.547 回答
2

对于设置具有多种颜色的属性文本字段占位符,

只需指定 Text ,

  //txtServiceText is your Textfield
 _txtServiceText.placeholder=@"Badal/ Shah";
    NSMutableAttributedString *mutable = [[NSMutableAttributedString alloc] initWithString:_txtServiceText.placeholder];
     [mutable addAttribute: NSForegroundColorAttributeName value:[UIColor whiteColor] range:[_txtServiceText.placeholder rangeOfString:@"Badal/"]]; //Replace it with your first color Text
    [mutable addAttribute: NSForegroundColorAttributeName value:[UIColor orangeColor] range:[_txtServiceText.placeholder rangeOfString:@"Shah"]]; // Replace it with your secondcolor string.
    _txtServiceText.attributedPlaceholder=mutable;

输出 :-

在此处输入图像描述

于 2016-05-20T05:52:29.320 回答
1

我需要保持占位符对齐,所以亚当的回答对我来说还不够。

为了解决这个问题,我使用了一个小变化,希望对你们中的一些人也有帮助:

- (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];
}
于 2013-06-10T10:13:56.523 回答
1
[txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"];
于 2014-04-23T09:34:04.623 回答
0

另一个不需要子类化的选项 - 将占位符留空,并在编辑按钮顶部放置标签。像管理占位符一样管理标签(一旦用户输入任何内容就清除..)

于 2010-12-06T22:34:28.823 回答
0

在斯威夫特 3

import UIKit

let TEXTFIELD_BLUE  = UIColor.blue
let TEXTFIELD_GRAY  = UIColor.gray

class DBTextField: UITextField {
    /// Tetxfield Placeholder Color
    @IBInspectable var palceHolderColor: UIColor = TEXTFIELD_GRAY
    func setupTextField () {
        self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "",
                                                            attributes:[NSForegroundColorAttributeName: palceHolderColor])
    }
}

class DBLocalizedTextField : UITextField {
    override func awakeFromNib() {
        super.awakeFromNib()
        self.placeholder = self.placeholder
    }
}
于 2017-12-07T05:38:28.790 回答
-10

我会建议另一种解决方案。由于占位符文本使用文本字段的默认字体设置,只需将初始字体颜色设置为您想要的占位符字体颜色即可。然后设置你的 UITextField 的委托并实现以下方法:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //set color for text input
    textField.textColor = [UIColor blackColor];
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    //set color for placeholder text
    textField.textColor = [UIColor redColor];
    return YES;
}

因此,如果用户开始在文本字段中输入,文本的颜色将变为黑色,并且在再次清除文本字段后,占位符文本将再次显示为红色。

干杯,安卡

于 2011-08-09T21:00:31.407 回答