Ios 如何为uialertview或UIAlertController中的特定单词着色?(SWIFT)

Ios 如何为uialertview或UIAlertController中的特定单词着色?(SWIFT),ios,colors,uialertview,Ios,Colors,Uialertview,有没有办法在uialertview中给某些特定的单词上色? 我的意思是,我能把红色这个词涂成红色,同时把绿色涂成绿色吗 有人能带我走正确的路吗 您可以使用NSAttributedString和UIAlertController: let strings = [["text" : "My String red\n", "color" : UIColor.redColor()], ["text" : "My string green", "color" : UIColor.greenCol

有没有办法在uialertview中给某些特定的单词上色? 我的意思是,我能把红色这个词涂成红色,同时把绿色涂成绿色吗


有人能带我走正确的路吗

您可以使用
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
我已经回答了这个问题-作为您可以使用的私有API的替代方案

pod'NativeUI/Alert',“~>1.0”


它看起来与本机警报完全相同,但足够可配置。

一般来说,您会使用NSAttributedString进行配置,但我认为UIAlertViews和UIAlertController不提供此功能,但您可能会找到一些地方:@luk2302 lol,wut?你是在告诉skyddict他不是在问控制器之前说这番话的?@Fogmeister是的!因为当时只是关于uialertviews的问题-我不确定他是否真的知道UIAlertController以及他所针对的操作系统。不过,他问的是uialertviews,而不是控制器。UIAlertController对我来说也没问题。但上面的示例仅显示红色文本“Red”。这很好,但是如何给特定的单词上色。在我的示例中,我应该有单词GREEN->GREEN,同时还有RED->RED。这是否适用于mentoined解决方案。@不推荐使用用于iOS8的luk2302 UIAlertView。如果您的目标是iOS8,那么无论如何都不应该使用UIAlertView。太好了,非常感谢您的努力。太好了。我可以在IOS8环境中使用UIAlertController。我的标题可能与UIAlertView有误。我还不熟悉OIS和版本。谢谢