问题
is there a way to color some specific words in uialertview ? I mean, can I color the word RED as red and at the same time GREEN as green ?
Can someone bring me on the right way?
回答1:
You could make use of NSAttributedString
and 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)
You use the key attributedMessage
to assign an attributed string for the message and the key attributedTitle
for the title.
I couldn't find a solution for UIAlertView
that works but all of them use private variables which is not good practice. You should know that UIAlertView
is deprecate from iOS 8 on, so if you are not targeting lower, you should not use it, instead use UIAlertController
来源:https://stackoverflow.com/questions/30661743/how-to-color-specific-words-in-a-uialertview-or-uialertcontroller-swift