how to color specific words in a uialertview or UIAlertController ? (SWIFT)

我与影子孤独终老i 提交于 2019-12-22 01:19:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!