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

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

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

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

 - (void)drawPlaceholderInRect:(CGRect)rect 

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

由于在iOS 6的UIViews中引入了属性string,所以可以像下面这样为占位符文本分配一个颜色:

 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. } 

容易和无痛,可能是一个简单的select。

 _placeholderLabel.textColor 

没有build议生产,苹果可能会拒绝您的提交。

您可以重写drawPlaceholderInRect:(CGRect)rect,以手动呈现占位符文本:

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

也许你想尝试这种方式,但苹果可能会警告你访问私人伊娃:

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

注意
MartinAlléus表示,iOS 7已经不适用了。

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

 UIColor *color = [UIColor lightTextColor]; YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}]; 

这工作在Swift <3.0:

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

在iOS 8.2和iOS 8.3 beta 4中testing

Swift 3:

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

在Swift中:

 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]) } 

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

 UIColor *color = [UIColor grayColor]; nameText.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Full Name" attributes:@{NSForegroundColorAttributeName:color}]; 

有了这个,我们可以在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"]; 

我已经遇到了这个问题。 在mycase下面的代码是正确的。

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

希望这可以帮助你。 它工作在7.0及以上。

你为什么不使用UIAppearance方法:

 [[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor whateverColorYouNeed]]; 

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

在这里输入图像说明

对于iOS 6.0 +

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

希望能帮助到你。

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

Swift 3.0 + Storyboard

为了更改故事板中的占位符颜色,请使用下一个代码创build一个扩展。 (随意更新此代码,如果您认为,它可以更清晰,更安全)。

 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) } } } 

在这里输入图像说明

对于Xamarin.iOS开发者,我从这个文档中find它https://developer.xamarin.com/api/type/Foundation.NSAttributedString/

 textField.AttributedPlaceholder = new NSAttributedString ("Hello, world",new UIStringAttributes () { ForegroundColor = UIColor.Red }); 

Swift版本。 可能会帮助某人。

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

在iOS7中处理垂直和水平alignment以及占位符的颜色。 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 

类别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 

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

该方法永远不会在UITextField上调用。

另请参见未调用UITextField上的drawTextInRect

你可以使用digdog的解决scheme。 由于我不确定这是否会超过苹果审查,我select了一个不同的解决scheme:用我自己的标签模仿占位符的行为覆盖文本字段。

虽然这有点乱。 代码看起来像这样(注意我在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; } 

iOS 6和更高版本在UITextField上提供“belongsPlaceholder”。 iOS 3.2和更高版本在NSMutableAttributedString上提供“setAttributes:range:”。

您可以执行以下操作:

  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; 

Iam新的Xcode和我find了一个方法来达到相同的效果。

我把uilabel放在所需格式的位置上,然后隐藏起来

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

我同意它的工作,而不是一个真正的解决scheme,但效果是相同的,从这个链接

注意:仍然可以在iOS 7上运行:|

我能做的最好的iOS7和更less的是:

 - (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]; } } 

对于那些使用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); } } 
 [txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"]; 

我需要保持占位符,所以亚当的答案是不够的。

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

 - (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]; } 

对于设置具有多种颜色的“已分配文本字段占位符”

只要指定文字,

  //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; 

输出: –

在这里输入图像说明

另一个不需要子类化的选项 – 将占位符留空,并在编辑button上放置一个标签。 像pipe理占位符一样pipe理标签(一旦用户input任何东西,就清除标签)

我会build议另一个解决scheme。 由于占位符文本使用文本字段的默认字体设置,只需将初始字体颜色设置为所需的占位符字体颜色即可。 然后设置您的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; } 

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

干杯,又名