我有一个实现深蓝色UITextField的设计,因为占位符文本默认是深灰色的颜色,我几乎不能弄清楚占位符文本说什么。
我当然在谷歌上搜索过这个问题,但我还没有想出一个解决方案,而使用Swift语言而不是Obj-c。
有没有一种方法来改变一个UITextField的占位符文本颜色使用Swift?
我有一个实现深蓝色UITextField的设计,因为占位符文本默认是深灰色的颜色,我几乎不能弄清楚占位符文本说什么。
我当然在谷歌上搜索过这个问题,但我还没有想出一个解决方案,而使用Swift语言而不是Obj-c。
有没有一种方法来改变一个UITextField的占位符文本颜色使用Swift?
当前回答
下面是我对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)
希望它能帮助到一些人!
其他回答
这段代码在Swift3中工作:
yourTextFieldName .setValue(UIColor.init(colorLiteralRed: 80/255, green: 80/255, blue: 80/255, alpha: 1.0), forKeyPath: "_placeholderLabel.textColor")
如果你有任何问题,请告诉我。
对于swift 4.2及以上版本,你可以这样做:
textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
就我而言,我做了以下事情:
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])
}
}
}
}
在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])
crubio对Swift 4的答案更新
选择UITextField并打开右边的标识检查器:
单击加号按钮并添加一个新的运行时属性:placeholderLabel。textColor(代替_placeholderLabel.textColor)
使用颜色作为类型并选择颜色。
如果您运行您的项目,您将看到这些更改。