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

时间:2009-08-27 10:36:20

标签: ios uitextfield

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

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

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

- (void)drawPlaceholderInRect:(CGRect)rect

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

32 个答案:

答案 0 :(得分:786)

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

答案 1 :(得分:235)

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

_placeholderLabel.textColor

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

答案 2 :(得分:194)

您可以覆盖drawPlaceholderInRect:(CGRect)rect,以手动呈现占位符文字:

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

答案 3 :(得分:164)

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

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

答案 4 :(得分:159)

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

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

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

答案 5 :(得分:126)

这适用于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])

Swift 4.2:

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

答案 6 :(得分:64)

在斯威夫特:

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

答案 7 :(得分:43)

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

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

答案 8 :(得分:42)

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

enter image description here

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

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

答案 9 :(得分:32)

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

[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"];

答案 10 :(得分:25)

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

目标C

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

适用于Swift 4.X

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

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

答案 11 :(得分:19)

为什么不使用UIAppearance方法:

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

答案 12 :(得分:17)

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

enter image description here

答案 13 :(得分:12)

适用于iOS 6.0 +

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

希望它有所帮助。

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

答案 14 :(得分:10)

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

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

答案 15 :(得分:9)

Swift版本。可能会对某人有所帮助。

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

答案 16 :(得分: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

答案 17 :(得分: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

答案 18 :(得分:5)

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;

答案 19 :(得分:4)

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

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

另见drawTextInRect on UITextField not called

您可以使用digdog的解决方案。由于我不确定这是否超过了Apples评论,我选择了另一种解决方案:使用我自己的标签覆盖文本字段,模仿占位符行为。

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

答案 20 :(得分:3)

我是xcode的新手,我找到了解决相同效果的方法。

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

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

        case 1:
            lblPassword.hidden=YES;
            break;

        default:
            break;
    }
}

我同意它的解决方案而不是真正的解决方案,但效果与此相同link

注意:仍适用于iOS 7:|

答案 21 :(得分:3)

此Swift 4.1解决方案

    textName.attributedPlaceholder = NSAttributedString(string: textName.placeholder!, attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])

答案 22 :(得分:2)

[txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"];

答案 23 :(得分: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];
  }
}

答案 24 :(得分: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);
    }
}

答案 25 :(得分:2)

在swift 3.X中

/assets/fonts/glyphicons-halflings-regular.woff

答案 26 :(得分:2)

带CAVEAT的Swift 5。

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

告诫您必须输入一个非空的String,其中“ DON'T_DELETE”在哪,即使该字符串是在其他代码中设置的也是如此。可能省去您五分钟的时间。

答案 27 :(得分: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];
}

答案 28 :(得分:1)

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

只需指定文字

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

输出: -

enter image description here

答案 29 :(得分:0)

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

答案 30 :(得分:0)

在Swift 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
    }
}

答案 31 :(得分:-9)

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

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

干杯, ANKA