代码之家  ›  专栏  ›  技术社区  ›  adam

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

  •  528
  • adam  · 技术社区  · 15 年前

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

    我更愿意这样做,而不使用普通文本作为占位符,也不必重写所有方法来模拟占位符的行为。

    - (void)drawPlaceholderInRect:(CGRect)rect
    

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

    31 回复  |  直到 8 年前
        1
  •  814
  •   user1071136    10 年前

    由于在iOS 6的UIView中引入了属性字符串,因此可以像下面这样为占位符文本指定颜色:

    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.
    }
    
        2
  •  239
  •   Jack    9 年前

    _placeholderLabel.textColor
    

    不建议生产,苹果可能会拒绝您的提交。

        3
  •  195
  •   Kuldeep Jayesh Lathiya    6 年前

    drawPlaceholderInRect:(CGRect)rect 因此,要手动呈现占位符文本,请执行以下操作:

    - (void) drawPlaceholderInRect:(CGRect)rect {
        [[UIColor blueColor] setFill];
        [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
    }
    
        4
  •  175
  •   Manju    11 年前

    UIColor *color = [UIColor lightTextColor];
    YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];
    
        5
  •  170
  •   ekscrypto    6 年前

    这适用于Swift<3.0:

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

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

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

    Swift 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
  •  158
  •   digdog    11 年前

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

    笔记
    据Martin Allus称,iOS 7不再适用。

        7
  •  83
  •   DZoki019 user1270061    5 年前

    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

    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)
            }
        }
    }
    
        8
  •  77
  •   clemens    7 年前

    迅速:

    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])
    }
    
        9
  •  43
  •   Fattie    10 年前

    UIColor *color = [UIColor grayColor];
    nameText.attributedPlaceholder =
       [[NSAttributedString alloc]
           initWithString:@"Full Name"
           attributes:@{NSForegroundColorAttributeName:color}];
    
        10
  •  35
  •   Ashu    5 年前

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

    目标C

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

    对于Swift 4.X

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

    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
    

    希望这对你有帮助。

        11
  •  32
  •   Yogi    8 年前

    有了它,我们可以在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"];
    
        12
  •  22
  •   Joshua Wolff    5 年前

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

    斯威夫特5

    textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor : UIColor.black])
    
        13
  •  21
  •   Matthias Waqas Memon    11 年前

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

    [[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor whateverColorYouNeed]];
    
        14
  •  18
  •   Petr Syrov    9 年前

    也在故事板中,没有一行代码

    enter image description here

        15
  •  12
  •   Fahim Parkar    10 年前

    适用于iOS 6.0+

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

    注: 苹果可能会拒绝(0.01%的几率)您的应用程序,因为我们正在访问私有API。两年以来,我在所有的项目中都使用了这个,但苹果并没有要求这样做。

        16
  •  10
  •   ManuQiao    8 年前

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

    textField.AttributedPlaceholder = new NSAttributedString ("Hello, world",new UIStringAttributes () { ForegroundColor =  UIColor.Red });
    
        17
  •  9
  •   Machado    8 年前

    class TextField: UITextField {
       override var placeholder: String? {
            didSet {
                let placeholderString = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
                self.attributedPlaceholder = placeholderString
            }
        }
    }
    
        18
  •  8
  •   Kuldeep Jayesh Lathiya    6 年前

    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
  •  7
  •   Mantosh Kumar    6 年前

    此解决方案适用于Swift 4.1

        textName.attributedPlaceholder = NSAttributedString(string: textName.placeholder!, attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])
    
        20
  •  6
  •   osxdirk    10 年前

    类别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
    
        21
  •  6
  •   Kuldeep Jayesh Lathiya    6 年前

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

    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
    
        22
  •  6
  •   HenryRootTwo    5 年前

    带警告的Swift 5。

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

    需要注意的是,您必须输入一个非空的 String 其中“DON'u DELETE”是,即使该字符串是在其他代码中设置的。也许可以帮你省去五分钟的头部扫描。

        23
  •  4
  •   Community CDub    7 年前

    最重要的 drawPlaceholderInRect: 这是正确的方法,但由于API(或文档)中的错误,它无法工作。

    UITextField .

    另见 drawTextInRect on UITextField not called

    不过这有点乱。 代码如下所示(注意,我在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;
    }
    
        24
  •  3
  •   Community CDub    4 年前

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

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

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

    我同意这是一个解决办法,不是一个真正的解决方案,但效果是一样的,我从中得到了它 link

    注:

        25
  •  2
  •   Aleksei Minaev    11 年前

    对于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];
      }
    }
    
        26
  •  2
  •   Wolfgang Schreurs    11 年前

    对于那些使用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);
        }
    }
    
        27
  •  1
  •   Tomer Even    11 年前

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

    - (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
  •   MD SHAHIDUL ISLAM    10 年前
    [txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"];
    
        29
  •  1
  •   Badal Shah    8 年前

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

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

        30
  •  0
  •   kolinko    14 年前