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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1340224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:20:22  来源:igfitidea点击:

iPhone UITextField - Change placeholder text color

iosuitextfield

提问by adam

I'd like to change the color of the placeholder text I set in my UITextFieldcontrols, to make it black.

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

I'd prefer to do this without using normal text as the placeholder and having to override all the methods to imitate the behaviour of a placeholder.

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

I believe if I override this method:

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

- (void)drawPlaceholderInRect:(CGRect)rect

then I should be able to do this. But I'm unsure how to access the actual placeholder object from within this method.

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

采纳答案by adam

You can override drawPlaceholderInRect:(CGRect)rectas such to manually render the placeholder text:

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

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

回答by user1071136

Since the introduction of attributed strings in UIViews in iOS 6, it's possible to assign a color to the placeholder text like this:

由于在 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.
}

回答by Hyman

Easy and pain-free, could be an easy alternative for some.

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

_placeholderLabel.textColor

Not suggested for production, Apple may reject your submission.

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

回答by Manju

You can Change the Placeholder textcolor to any color which you want by using the below code.

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

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

回答by digdog

Maybe you want to try this way, but Apple might warn you about accessing private ivar:

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

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

NOTE
This is not working on iOS 7 anymore, according to Martin Alléus.

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

回答by Tomino

This works in Swift <3.0:

这适用于 Swift <3.0:

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

Tested in iOS 8.2 and iOS 8.3 beta 4.

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

Swift 3:

斯威夫特 3:

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

Swift 4:

斯威夫特 4:

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

Swift 4.2:

斯威夫特 4.2:

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

回答by Beninho85

In Swift:

在斯威夫特:

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

In Swift 4.0:

在 Swift 4.0 中:

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

回答by Nik Kov

Swift 3.0 + Storyboard

Swift 3.0 + 故事板

In order to change placeholder color in storyboard, create an extension with next code. (feel free to update this code, if you think, it can be clearer and safer).

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

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 version

斯威夫特 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 version

斯威夫特 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)
        }
    }
}

回答by Gaurav Gilani

The following only with iOS6+ (as indicated in Alexander W's comment):

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

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

回答by Ashu

I had already faced this issue. In my case below code is correct.

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

Objective C

目标 C

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

For Swift 4.X

对于 Swift 4.X

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

For iOS 13 Swift Code

适用于 iOS 13 Swift 代码

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

You can also use below code for iOS 13

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

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

Hope, this may help you.

希望,这可以帮助你。