如何在uialertview或UIAlertController中为特定单词着色?(迅速)

mcf*_*oft 0 colors uialertview ios

是否有办法为uialertview中的某些特定单词着色?我的意思是,我可以将RED这个词换成红色,同时将GREEN换成绿色吗?

在此输入图像描述

有人能以正确的方式带我吗?

Teo*_*Teo 12

你可以利用NSAttributedStringUIAlertController:

    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)
Run Code Online (Sandbox Code Playgroud)

您可以使用该键attributedMessage为消息分配属性字符串,并attributedTitle为标题指定键.

我无法找到解决方案UIAlertView,但所有这些都使用私有变量,这不是一个好习惯.您应该知道UIAlertView从iOS 8开始弃用,因此如果您没有降低目标,则不应使用它,而应使用它UIAlertController