如何在 swift 中为整个应用程序的 UITextField 设置全局占位符颜色?

How to set a global Place holder colour for a UITextField for the whole app in swift?

我正在创建一个应用程序,其中我使用了多个 UITextfield。我知道如何更改单个文本字段的 placeholder 颜色。

textField.attributedPlaceholder = NSAttributedString(string: "Username", attributes: [NSForegroundColorAttributeName: UIColor.redColor()])

但我想更改整个应用程序中所有 UITextField 的占位符颜色。我的应用程序有超过 50 个 UIViewControllers,其中超过 25 个有文本字段(每个屏幕 2 到 22 个)。我想要一个可以在一个地方全局使用的代码,这样我就不需要去每个视图控制器并手动更改它。

如果您有任何其他替代方法来完成这项工作,请告诉我。

我正在使用 xcode 7.1.1 swift 2.0

更新: 默认情况下,占位符颜色设置为浅灰色。我们有什么办法可以调整默认行为并将其更改为任何其他颜色?

我们如何访问和更改此默认代码?

用你的 NSAttributedString 声明一个宏。

将 Attributed 字符串提供给所有你想要的文本字段。

这样当你在宏中改变时,会反映在所有地方..

查看以下内容。

let CommonTextFieldAttr : NSDictionary = [NSForegroundColorAttributeName:UIColor.redColor()]

并在文本字段属性中使用它。

textField?.attributedPlaceholder = NSAttributedString(string: "sdfa",attributes: CommonTextFieldAttr as? [String : AnyObject])

希望对您有所帮助..

创建扩展方法

extension String {

func toAttributedString(font font:UIFont!, kerning: CGFloat!, color:UIColor!) -> NSAttributedString {
    return NSAttributedString(string: self as String, font: font, kerning: kerning, color: color)!
}
}

extension NSAttributedString {

convenience init?(string text:String, font:UIFont!, kerning: CGFloat!, color:UIColor!) {
    self.init(string: text, attributes: [NSKernAttributeName:kerning, NSFontAttributeName:font, NSForegroundColorAttributeName:color])
}
}

用法示例

/ Example Usage
var testString: String = "Hi Kautham"

var testAttributedString: NSAttributedString = testString.toAttributedString(font: UIFont.boldSystemFontOfSize(20), kerning: 2.0, color: UIColor.whiteColor())


let label = UILabel(frame: CGRect(x: 50, y: 50, width: 200, height: 20))

label.attributedText = testAttributedString
 self.view.addSubview(label)