【问题标题】:How to set a global Place holder colour for a UITextField for the whole app in swift?如何快速为整个应用程序的 UITextField 设置全局占位符颜色?
【发布时间】:2016-04-18 07:39:09
【问题描述】:

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

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

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

如果您有其他方法可以完成这项工作,请告诉我。

我正在使用xcode 7.1.1swift 2.0

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

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

【问题讨论】:

标签: ios swift swift2 uitextfield appdelegate


【解决方案1】:

创建扩展方法

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)

【讨论】:

  • 感谢您的回答,这真的很有帮助。
  • @KauthamMurugan - 很高兴听到兄弟,它有效,因为我没有测试过这个
【解决方案2】:

用你的 NSAttributedString 声明一个宏。

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

这样当你在Macro改变时,会体现在所有地方..

查看以下内容。

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

并在 Textfield 属性中使用它。

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

希望对你有帮助..

【讨论】:

  • 问题和swift有关,可以自定义回答吗
  • @Balaji 感谢您的关注。但我已经知道这种方法了。问题是,要设置新属性,我必须在所有视图控制器中为我讨厌的每个文本字段使用代码的第二行。我在一个视图控制器中有多个文本字段,最多 22 个。
猜你喜欢
  • 2013-09-12
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 2014-06-03
  • 2019-01-03
  • 2016-08-27
  • 2012-04-12
  • 1970-01-01
相关资源
最近更新 更多