我正在创建一个应用程序,其中我使用多个 UITextfield
。我知道如何更改单个文本字段的 placeholder
颜色。
textField.attributedPlaceholder = NSAttributedString(string: "Username", attributes: [NSForegroundColorAttributeName: UIColor.redColor()])
。
但我想更改整个应用程序中所有 UITextField
的占位符颜色。我的应用有超过 50 个 UIViewControllers
,其中超过 25 个有 textFields(每个屏幕 2 到 22 个)。我想要一个可以在一个地方全局使用的代码,这样我就不需要转到每个 View Controller 并手动更改它。
如果您有任何其他替代方法来完成这项工作,请告诉我。
我正在使用 xcode 7.1.1
swift 2.0
更新: 默认情况下,占位符颜色设置为浅灰色。我们有什么办法可以调整默认行为并将其更改为任何其他颜色?
我们如何访问和更改此默认代码?
最佳答案
创建扩展方法
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)
关于ios - 如何快速为整个应用程序的 UITextField 设置全局占位符颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36687995/