使用Swift更改占位符文本颜色


226

我有一个实现深蓝色的设计UITextField,因为默认情况下,占位符文本为深灰色,所以我几乎无法分辨出占位符文本的含义。

我已经用谷歌搜索了这个问题,但是在使用Swift语言而不是Obj-c时我还没有提出解决方案。

有没有一种方法可以在UITextField使用Swift 的情况下更改占位符文本的颜色?

Answers:


501

您可以使用属性字符串设置占位符文本。通过:传递所需的颜色attributes

var myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
myTextField.backgroundColor = .blue
myTextField.attributedPlaceholder = NSAttributedString(string: "placeholder text",
                             attributes: [NSForegroundColorAttributeName: UIColor.yellow])

对于Swift 3+,请使用以下命令:

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

对于Swift 4.2,请使用以下命令:

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

iOS 11 SDK-密钥没有前台颜色:self.emailTextField?.attributedPlaceholder = NSAttributedString(字符串:“占位符文本”,属性:[NSAttributedStringKey.foregroundColor:UIColor.white])
Matthew Ferguson

@MatthewFerguson,我刚刚尝试过,它可以工作。您有Xcode 9的发行版本吗?什么是emailTextField
vacawama

2
@vacawama。感谢您的交流。旧版项目,从App Store更新了我的Xcode-版本9.0(9A235),最后提出了self.passwordTextField?.attributedPlaceholder = NSAttributedString(string:“ PASSWORD”,属性:[NSForegroundColorAttributeName:UIColor.white]的解决方案)
马修·弗格森

3
适用于iOS 11 SDK的应用myTextField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName: UIColor.white])
Gema Megantara

1
有没有一种方法可以设置颜色而不设置字符串?
ScottyBlades

285

您可以使用Interface Builder快速完成此操作,而无需添加任何代码。

选择,UITextField然后打开右侧的身份检查器:

在此处输入图片说明

单击加号按钮并添加新的运行时属性:

placeholderLabel.textColor(快速4)

_placeholderLabel.textColor(Swift 3或以下)

使用颜色作为类型,然后选择颜色。

而已。

在再次运行应用程序之前,您不会看到结果。


1
真实的,但它是一种黑客,因为placeholderLabel.textColor财产是私有的...
弗雷德里克·阿达

1
我们使用该类的私有属性,会否拒绝该应用程序?
火播

2
不幸的是,这似乎至少在iOS 10上不起作用。
nickdnk

2
@nickdnk不正确。现在,我已经在iOS 10.2.1上进行了测试,并且可以正常工作。:)
Andrej

2
如果苹果将改变内部实施方式,则可能会导致意外崩溃。)
Vlad17年

127

UITextField像这样创建扩展:

extension UITextField{
   @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: newValue!])
        }
    }
}

并在您的情节提要或.xib中。你会看见

在此处输入图片说明


11
Warning️ 警告:如果您决定读取该属性,此扩展名将使您的程序崩溃!如果从属性的getter返回计算属性本身的值,则将从getter内再次调用getter,从而导致无限递归。(请参阅:stackoverflow.com/a/42334711/2062785placeHolderColor
Mischa

1
要解决此问题并获得预期的行为(即正确的占位符颜色),请获取的attributedString第一个字母(如果不为空),然后返回其文本颜色,否则返回nil
Mischa

为什么在框中显示2种颜色。我以为这是暗模式,但事实并非如此。
asreerama

27

在Swift 3.0中,使用

let color = UIColor.lightText
textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder, attributes: [NSForegroundColorAttributeName : color])

在Siwft 5.0中+使用

let color = UIColor.lightText
let placeholder = textField.placeholder ?? "" //There should be a placeholder set in storyboard or elsewhere string or pass empty
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor : color])

24

这段代码在Swift3中工作:

yourTextFieldName .setValue(UIColor.init(colorLiteralRed: 80/255, green: 80/255, blue: 80/255, alpha: 1.0), forKeyPath: "_placeholderLabel.textColor")

让我知道您是否有任何问题。


由于某种原因,当我尝试对1个以上的textField执行操作时,此操作会崩溃。第一个工作正常,然后在所有后续textField上崩溃。不知道为什么,但是我希望我可以使用这种方法,因为它是最简单,最易读的方法
Tommy K,

无需使用setValue来访问私有财产。使用正确的公共API。
rmaddy

这是最好的答案。。。
reza_khalafi

Xcode 10 / Swift 5文字语法:#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
Lal Krishna

15

要为UITextField您的应用中的所有内容一次设置占位符颜色,您可以执行以下操作:

UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.redColor()

这将为TextField整个应用程序中的所有占位符设置所需的颜色。但仅自iOS 9起可用。

swift的iOS 9之前没有出现方法whenWhen,但是您可以使用Swift中此处提供的解决方案之一


这不仅会更改占位符颜色,还会更改文本颜色。
Timur Suleimanov

7

就我而言,我使用Swift 4

我为UITextField创建扩展

extension UITextField {
    func placeholderColor(color: UIColor) {
        let attributeString = [
            NSAttributedStringKey.foregroundColor: color.withAlphaComponent(0.6),
            NSAttributedStringKey.font: self.font!
            ] as [NSAttributedStringKey : Any]
        self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: attributeString)
    }
}

yourField.placeholderColor(color:UIColor.white)


6

Xcode 9.2 Swift 4

extension UITextField{
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: newValue!])
        }
    }
}

2
这行不通。吸气剂将导致无限递归。
rmaddy

2
这在swift 4中工作正常。我在代码中创建了断点,并检查了它。无限递归没有发生。
R. Mohan

1
请勿使用此功能。这将导致无限递归。试试:print(textField.placeHolderColor)
David Rees

5

斯威夫特4:

txtControl.attributedPlaceholder = NSAttributedString(string: "Placeholder String...",attributes: [NSAttributedStringKey.foregroundColor: UIColor.gray])

目标-C:

UIColor *color = [UIColor grayColor];
txtControl.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Placeholder String..." attributes:@{NSForegroundColorAttributeName: color}];

4

这是我对Swift 4的快速实现:

extension UITextField {
    func placeholderColor(_ color: UIColor){
        var placeholderText = ""
        if self.placeholder != nil{
            placeholderText = self.placeholder!
        }
        self.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedStringKey.foregroundColor : color])
    }
}

用途像:

streetTextField?.placeholderColor(AppColor.blueColor)

希望对别人有帮助!


Swift 4.2:self.attributedPlaceholder = NSAttributedString(字符串:placeholderText,属性:[NSAttributedString.Key.foregroundColor:颜色])
肖恩·史坦斯

4

Swift 3(可能是2),您可以在UITextField子类中的占位符上覆盖didSet,以对其应用属性,方法是:

override var placeholder: String? {

    didSet {
        guard let tmpText = placeholder else {
            self.attributedPlaceholder = NSAttributedString(string: "")
            return
        }

        let textRange = NSMakeRange(0, tmpText.characters.count)
        let attributedText = NSMutableAttributedString(string: tmpText)
        attributedText.addAttribute(NSForegroundColorAttributeName , value:UIColor(white:147.0/255.0, alpha:1.0), range: textRange)

        self.attributedPlaceholder = attributedText
    }
}

4

对于斯威夫特

创建UITextField扩展

extension UITextField{

    func setPlaceHolderColor(){
        self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: [NSForegroundColorAttributeName : UIColor.white])
    }
}

如果是从情节提要中设置的。

extension UITextField{
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor : newValue!])
        }
    }
}

3

对于Swift 3和3.1,这可以很好地工作:

passField.attributedPlaceholder = NSAttributedString(string: "password", attributes: [NSForegroundColorAttributeName: UIColor.white])

3

对于Swift 4.0,X-code 9.1版本或iOS 11,您可以使用以下语法来设置不同的占位符颜色

textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])

3

我很惊讶地看到这里有多少糟糕的解决方案。

这是一个始终有效的版本。

斯威夫特4.2

extension UITextField{
    @IBInspectable var placeholderColor: UIColor {
        get {
            return self.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .lightText
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string: self.placeholder ?? "", attributes: [.foregroundColor: newValue])
        }
    }
}

提示:如果在设置颜色后更改占位符文本,则颜色将重置。


3

只需将以下代码写入Appdelegate的didFinishLaunchingWithOptions方法即可,如果您想更改Swift 4.2编写的整个应用程序,请使用此代码

UILabel.appearance(whenContainedInInstancesOf: [UITextField.self]).textColor = UIColor.white


1

对于Swift 4.2及更高版本,您可以按以下步骤操作:

textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])

1

就我而言,我已经完成以下工作:

extension UITextField {
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            if let color = self.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor {
                return color
            }
            return nil
        }
        set (setOptionalColor) {
            if let setColor = setOptionalColor {
                let string = self.placeholder ?? ""
                self.attributedPlaceholder = NSAttributedString(string: string , attributes:[NSAttributedString.Key.foregroundColor: setColor])
            }
        }
    }
}

1

我在这里编写UITextField的所有UIDesignable。借助此代码,您可以从情节提要中的UI文件检查器直接访问它

@IBDesignable
class CustomTextField: UITextField {

@IBInspectable var leftImage: UIImage? {
    didSet {
        updateView()
    }
}

@IBInspectable var leftPadding: CGFloat = 0 {
    didSet {
        updateView()
    }
}

@IBInspectable var rightImage: UIImage? {
    didSet {
        updateView()
    }
}

@IBInspectable var rightPadding: CGFloat = 0 {
    didSet {
        updateView()
    }
}

private var _isRightViewVisible: Bool = true
var isRightViewVisible: Bool {
    get {
        return _isRightViewVisible
    }
    set {
        _isRightViewVisible = newValue
        updateView()
    }
}

func updateView() {
    setLeftImage()
    setRightImage()

    // Placeholder text color
    attributedPlaceholder = NSAttributedString(string: placeholder != nil ?  placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: tintColor])
}

func setLeftImage() {
    leftViewMode = UITextField.ViewMode.always
    var view: UIView

    if let image = leftImage {
        let imageView = UIImageView(frame: CGRect(x: leftPadding, y: 0, width: 20, height: 20))
        imageView.image = image
        // Note: In order for your image to use the tint color, you have to select the image in the Assets.xcassets and change the "Render As" property to "Template Image".
        imageView.tintColor = tintColor

        var width = imageView.frame.width + leftPadding

        if borderStyle == UITextField.BorderStyle.none || borderStyle == UITextField.BorderStyle.line {
            width += 5
        }

        view = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 20))
        view.addSubview(imageView)
    } else {
        view = UIView(frame: CGRect(x: 0, y: 0, width: leftPadding, height: 20))
    }

    leftView = view
}

func setRightImage() {
    rightViewMode = UITextField.ViewMode.always

    var view: UIView

    if let image = rightImage, isRightViewVisible {
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        imageView.image = image
        // Note: In order for your image to use the tint color, you have to select the image in the Assets.xcassets and change the "Render As" property to "Template Image".
        imageView.tintColor = tintColor

        var width = imageView.frame.width + rightPadding

        if borderStyle == UITextField.BorderStyle.none || borderStyle == UITextField.BorderStyle.line {
            width += 5
        }

        view = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 20))
        view.addSubview(imageView)

    } else {
        view = UIView(frame: CGRect(x: 0, y: 0, width: rightPadding, height: 20))
    }

    rightView = view
}


@IBInspectable public var borderColor: UIColor = UIColor.clear {
    didSet {
        layer.borderColor = borderColor.cgColor
    }
}

@IBInspectable public var borderWidth: CGFloat = 0 {
    didSet {
        layer.borderWidth = borderWidth
    }
}

@IBInspectable public var cornerRadius: CGFloat = 0 {
    didSet {
        layer.cornerRadius = cornerRadius
    }
}
@IBInspectable public var bottomBorder: CGFloat = 0 {
    didSet {
       borderStyle = .none
        layer.backgroundColor = UIColor.white.cgColor

        layer.masksToBounds = false
     //   layer.shadowColor = UIColor.gray.cgColor
        layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        layer.shadowOpacity = 1.0
        layer.shadowRadius = 0.0
    }
}
@IBInspectable public var bottomBorderColor : UIColor = UIColor.clear {
    didSet {

        layer.shadowColor = bottomBorderColor.cgColor
        layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        layer.shadowOpacity = 1.0
        layer.shadowRadius = 0.0
    }
}
/// Sets the placeholder color
@IBInspectable var placeHolderColor: UIColor? {
    get {
        return self.placeHolderColor
    }
    set {
        self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: newValue!])
    }
}

}

0

对于斯威夫特

func setPlaceholderColor(textField: UITextField, placeholderText: String) {
    textField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.pelorBlack])
}

您可以使用它;

self.setPlaceholderColor(textField: self.emailTextField, placeholderText: "E-Mail/Username")

0

它更多地是关于个性化textField的,但是无论如何,我将共享从另一页获得的代码并使它更好一点:

import UIKit
extension UITextField {
func setBottomLine(borderColor: UIColor, fontColor: UIColor, placeHolderColor:UIColor, placeHolder: String) {
    self.borderStyle = UITextBorderStyle.none
    self.backgroundColor = UIColor.clear
    let borderLine = UIView()
    let height = 1.0
    borderLine.frame = CGRect(x: 0, y: Double(self.frame.height) - height, width: Double(self.frame.width), height: height)
    self.textColor = fontColor
    borderLine.backgroundColor = borderColor
    self.addSubview(borderLine)
    self.attributedPlaceholder = NSAttributedString(
        string: placeHolder,
        attributes: [NSAttributedStringKey.foregroundColor: placeHolderColor]
    )
  }
}

您可以像这样使用它:

self.textField.setBottomLine(borderColor: lineColor, fontColor: fontColor, placeHolderColor: placeHolderColor, placeHolder: placeHolder)

知道您已UITextField连接到ViewController

资料来源:http : //codepany.com/blog/swift-3-custom-uitextfield-with-single-line-input/


0

在此处输入图片说明

对于目标C

UIColor *color = [UIColor colorWithRed:0.44 green:0.44 blue:0.44 alpha:1.0];
 emailTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Friend's Email" attributes:@{NSForegroundColorAttributeName: color}];

对于Swift

emailTextField.attributedPlaceholder = NSAttributedString(string: "Friend's Email",
                             attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])

0

用于更改占位符文本颜色的目标C代码。

首先导入这个objc / runtime类-

#import <objc/runtime.h>

然后替换您的文本字段名称-

Ivar ivar =  class_getInstanceVariable([UITextField class], "_placeholderLabel");
UILabel *placeholderLabel = object_getIvar(YourTxtField, ivar);
placeholderLabel.textColor = [UIColor whiteColor];


0

适用于iOS13

+(void)ChangeplaceholderColor :(UITextField *)TxtFld andColor:(UIColor*)color { 
    NSMutableAttributedString *placeholderAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:TxtFld.attributedPlaceholder];
       [placeholderAttributedString addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, [placeholderAttributedString length])];
       TxtFld.attributedPlaceholder = placeholderAttributedString;

}

0

在Swift中像这样使用

 let placeHolderText = textField.placeholder ?? ""
 let str = NSAttributedString(string:placeHolderText!, attributes: [NSAttributedString.Key.foregroundColor :UIColor.lightGray])
 textField.attributedPlaceholder = str

在目标C中

NSString *placeHolder = [textField.placeholder length]>0 ? textField.placeholder: @"";
NSAttributedString *str = [[NSAttributedString alloc] initWithString:placeHolder attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }];
textField.attributedPlaceholder = str;

0
    extension UITextField{
            @IBInspectable var placeHolderColor: UIColor? {
                get {
                    return self.placeHolderColor
                }
                set {
                    self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ?
        self.placeholder! : "",
        attributes:[NSAttributedString.Key.foregroundColor : newValue!])
                }
            } 
}

-1

使用它来添加属性占位符:

let attributes : [String : Any]  = [ NSForegroundColorAttributeName: UIColor.lightGray,
                                     NSFontAttributeName : UIFont(name: "Helvetica Neue Light Italic", size: 12.0)!
                                   ]
x_textfield.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes:attributes)

-1

对于Swift 4

txtField1.attributedPlaceholder = NSAttributedString(string: "-", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])

1
这是几个先前答案的重复。无需发布重复的答案。
rmaddy

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.