我有一个实现深蓝色UITextField的设计,因为占位符文本默认是深灰色的颜色,我几乎不能弄清楚占位符文本说什么。

我当然在谷歌上搜索过这个问题,但我还没有想出一个解决方案,而使用Swift语言而不是Obj-c。

有没有一种方法来改变一个UITextField的占位符文本颜色使用Swift?


当前回答

它更多的是个性化你的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/

其他回答

为迅速

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

你可以用这个;

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

Swift 3(可能是2),你可以覆盖didSet占位符在UITextField子类上应用属性,这样:

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

对于Swift 3和3.1,这工作得非常好:

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

您可以使用Interface Builder快速完成此任务,而无需添加一行代码。

选择UITextField并打开右边的标识检查器:

点击加号按钮,添加一个新的运行时属性:

placeholderLabel。textColor (Swift 4)

_placeholderLabel。textColor (Swift 3或更少)

使用颜色作为类型并选择颜色。

就是这样。

你不会看到结果,直到你再次运行你的应用程序。

对于目标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}];

迅速:

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