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

ada*_*dam 550 uitextfield ios

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

我更喜欢这样做而不使用普通文本作为占位符,并且必须覆盖所有方法来模仿占位符的行为.

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

- (void)drawPlaceholderInRect:(CGRect)rect
Run Code Online (Sandbox Code Playgroud)

然后我应该能够做到这一点.但我不确定如何从此方法中访问实际的占位符对象.

use*_*136 798

自从在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.
}
Run Code Online (Sandbox Code Playgroud)

  • `attributionPlaceholder`的文档说它使用文本属性,颜色除外. (5认同)
  • 它也值得在一个respondsToSelector调用中包装它 - 因为没有它,这个代码将在6.0之前的部署目标(无法识别的选择器发送到实例)上崩溃 (4认同)
  • 在iOS 7上,我收到了这样的错误:`[<UITextField 0x11561d90> valueForUndefinedKey:]:此类不是键_字段的键值编码兼容. (3认同)
  • 这很好 - 但是请记住,在此工作之前,您需要在IB中设置占位符值 (2认同)
  • 根据反馈更新答案的绝佳答案和荣誉 (2认同)

Jac*_*ack 239

容易和无痛,可能是一些容易的替代品.

_placeholderLabel.textColor
Run Code Online (Sandbox Code Playgroud)

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

  • 不要使用这种方法,我已经使用过这个和itune商店,拒绝了我的申请. (41认同)
  • 也许将文本添加到您的答案中以便快速复制和粘贴._placeholderLabel.textColor (11认同)
  • @jungledev`_placeholderLabel`是一个私人财产.此解决方案可能因使用私有API而被拒绝. (2认同)

ada*_*dam 194

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

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

  • 绝对不要做Koteg所说的.永远不要通过类别覆盖方法.EVER (52认同)
  • 像`[self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];`可能更好.这样你就会尊重`textAlignment`属性.我已将此添加到我的[SSTextField](https://github.com/samsoffes/sstoolkit/blob/master/SSToolkit/SSTextField.h)类中.随意在您的项目中使用. (44认同)
  • @JoshuaWeinberg你的消化背后有什么特别的原因. (8认同)
  • 在iOS7中,您可以使用CGRectInset(rect,0,(rect.size.height - self.font.lineHeight)/ 2.0)来更改矩形,以使文本垂直居中. (8认同)
  • 不支持@Krishnan在类别中实现重复方法,并且您永远不能确定将调用哪个方法,或者是否同时调用它们,或者它们将被调用的顺序. (5认同)
  • 更好的方法是使用:`[self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeClip alignment:self.textAlignment]`所以textAlignment也会传播. (3认同)
  • 使用`self.font`而不是`[UIFont systemFontOfSize:16]`会更好,因此更改textfields字体仍会传播到占位符. (2认同)

小智 168

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

UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];
Run Code Online (Sandbox Code Playgroud)

  • 最佳答案建议.工作,并使用文档化的API. (6认同)
  • 你如何为UISearchBar做这项工作?没有attributionPlaceholder属性. (2认同)

dig*_*dog 159

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

[self.myTextField setValue:[UIColor darkGrayColor] 
                forKeyPath:@"_placeholderLabel.textColor"];
Run Code Online (Sandbox Code Playgroud)

注:
根据MartinAlléus的说法,这不再适用于iOS 7.

  • 如果它被批准或不是真的,那真的不重要.重要的是,这可能会在未来的操作系统更新中破坏您的应用程序. (30认同)
  • 我试过,AppStore评论上帝似乎对这个很好. (19认同)
  • 这不是应用程序商店的安全,如果不鼓励,您不能保证获得批准或保持这些技术的批准. (9认同)
  • 我在我的应用程序中使用此方法.审查没问题.所以我觉得使用它很好. (6认同)
  • iOS 7没有任何问题...尽管有笔记但我试了一下它似乎工作正常,我在过去使用这种方法没有问题. (2认同)
  • 这总是一个坏主意,现在在iOS 13上已被打破:`禁止访问UITextField的_placeholderLabel ivar。这是一个应用程序错误` (2认同)

Tom*_*ino 142

这适用于Swift <3.0:

myTextField.attributedPlaceholder = 
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
Run Code Online (Sandbox Code Playgroud)

在iOS 8.2和iOS 8.3 beta 4中测试过.

斯威夫特3:

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.red])
Run Code Online (Sandbox Code Playgroud)

斯威夫特4:

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

Swift 4.2:

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
Run Code Online (Sandbox Code Playgroud)


Ben*_*o85 69

在Swift中:

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

在Swift 4.0中:

if let placeholder = yourTextField.placeholder {
    yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder, 
        attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
}
Run Code Online (Sandbox Code Playgroud)


Nik*_*Kov 54

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Swift 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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Gau*_*ani 43

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

UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =
   [[NSAttributedString alloc]
       initWithString:@"Full Name"
       attributes:@{NSForegroundColorAttributeName:color}];
Run Code Online (Sandbox Code Playgroud)

  • 是的,现在只使用iOS6 +. (7认同)

Uma*_*avi 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"];
Run Code Online (Sandbox Code Playgroud)


Ash*_*shu 28

我已经遇到过这个问题.在我的情况下,代码是正确的.

目标C.

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

对于Swift 4.X

tf_mobile.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")
Run Code Online (Sandbox Code Playgroud)

希望,这可能会对你有所帮助.

  • iOS 13 这个被限制了不能再用了 (2认同)

Val*_*der 19

你为什么不用UIAppearance方法:

[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor whateverColorYouNeed]];
Run Code Online (Sandbox Code Playgroud)


Pet*_*rov 18

同样在你的故事板中,没有单行代码

在此输入图像描述

  • 这是非常普遍的.一旦你知道它到处使用它;) (2认同)
  • @Yawar您可以在Xcode中使用视图层次结构检查器,或者在调试器中内省视图. (2认同)

Fah*_*kar 12

适用于iOS 6.0 +

[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.

注意: Apple可能会拒绝(0.01%几率)您的应用,因为我们正在访问私有API.我在两年后的所有项目中都使用了这个,但Apple没有要求这个.


Man*_*iao 10

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

textField.AttributedPlaceholder = new NSAttributedString ("Hello, world",new UIStringAttributes () { ForegroundColor =  UIColor.Red });
Run Code Online (Sandbox Code Playgroud)


Max*_*hii 9

Swift版本.可能它会帮助某人.

class TextField: UITextField {
   override var placeholder: String? {
        didSet {
            let placeholderString = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
            self.attributedPlaceholder = placeholderString
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


MAh*_*ngh 9

迅速3.X

textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes:[NSForegroundColorAttributeName: UIColor.black])
Run Code Online (Sandbox Code Playgroud)

迅速5

textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor : UIColor.black])
Run Code Online (Sandbox Code Playgroud)


Man*_*mar 7

这个 Swift 4.1 的解决方案

    textName.attributedPlaceholder = NSAttributedString(string: textName.placeholder!, attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])
Run Code Online (Sandbox Code Playgroud)


Wil*_*wer 6

iOS 6或更高版本提供attributedPlaceholderUITextField.的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;
Run Code Online (Sandbox Code Playgroud)


aum*_*are 6

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

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

OBJ-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
Run Code Online (Sandbox Code Playgroud)


osx*_*irk 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
Run Code Online (Sandbox Code Playgroud)


Hen*_*Two 6

带有警告的斯威夫特 5。

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

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