如何为 uialertview 或 UIAlertController 中的特定单词着色? (SWIFT)
how to color specific words in a uialertview or UIAlertController ? (SWIFT)
有没有办法在 uialertview 中给一些特定的单词上色?
我的意思是,我可以将 RED 一词涂成红色,同时将 GREEN 涂成绿色吗?
有人能带我走正确的路吗?
您可以使用 NSAttributedString
和 UIAlertController
:
let strings = [["text" : "My String red\n", "color" : UIColor.redColor()], ["text" : "My string green", "color" : UIColor.greenColor()]];
var attributedString = NSMutableAttributedString()
for configDict in strings {
if let color = configDict["color"] as? UIColor, text = configDict["text"] as? String {
attributedString.appendAttributedString(NSAttributedString(string: text, attributes: [NSForegroundColorAttributeName : color]))
}
}
let alert = UIAlertController(title: "Title", message: "", preferredStyle: .Alert)
alert.setValue(attributedString, forKey: "attributedMessage")
let cancelAction = UIAlertAction(title: "Cancel",
style: .Default) { (action: UIAlertAction!) -> Void in
}
presentViewController(alert,
animated: true,
completion: nil)
您使用键 attributedMessage
为消息分配属性字符串,并使用键 attributedTitle
为标题。
我找不到适用于 UIAlertView
的解决方案,但它们都使用私有变量,这不是好的做法。你应该知道 UIAlertView
从 iOS 8 开始被弃用,所以如果你的目标不是更低,你不应该使用它,而是使用 UIAlertController
我已经在那里回答了 - as an alternative to private API you could use https://github.com/AntonPoltoratskyi/NativeUI
pod 'NativeUI/Alert', '~> 1.0'
它看起来很像原生警报,但足够可配置。
有没有办法在 uialertview 中给一些特定的单词上色? 我的意思是,我可以将 RED 一词涂成红色,同时将 GREEN 涂成绿色吗?
有人能带我走正确的路吗?
您可以使用 NSAttributedString
和 UIAlertController
:
let strings = [["text" : "My String red\n", "color" : UIColor.redColor()], ["text" : "My string green", "color" : UIColor.greenColor()]];
var attributedString = NSMutableAttributedString()
for configDict in strings {
if let color = configDict["color"] as? UIColor, text = configDict["text"] as? String {
attributedString.appendAttributedString(NSAttributedString(string: text, attributes: [NSForegroundColorAttributeName : color]))
}
}
let alert = UIAlertController(title: "Title", message: "", preferredStyle: .Alert)
alert.setValue(attributedString, forKey: "attributedMessage")
let cancelAction = UIAlertAction(title: "Cancel",
style: .Default) { (action: UIAlertAction!) -> Void in
}
presentViewController(alert,
animated: true,
completion: nil)
您使用键 attributedMessage
为消息分配属性字符串,并使用键 attributedTitle
为标题。
我找不到适用于 UIAlertView
的解决方案,但它们都使用私有变量,这不是好的做法。你应该知道 UIAlertView
从 iOS 8 开始被弃用,所以如果你的目标不是更低,你不应该使用它,而是使用 UIAlertController
我已经在那里回答了
pod 'NativeUI/Alert', '~> 1.0'
它看起来很像原生警报,但足够可配置。