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

问题描述 投票:0回答:2

是否可以在uialertview中为某些特定的单词着色?我的意思是,我可以将单词RED涂成红色,同时将GREEN涂成绿色吗?

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS82WmJJTi5qcGcifQ==” alt =“在此处输入图像描述”>

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

ios colors uialertview
2个回答
14
投票

您可以使用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)

您使用键attributedMessage分配消息的属性字符串,并使用键attributedTitle分配标题。

我找不到适用于UIAlertView的解决方案,但它们都使用私有变量,这不是一个好习惯。您应该知道UIAlertView从iOS 8开始不推荐使用,因此,如果您的目标不是较低版本,则不要使用它,而应使用UIAlertController


0
投票

我已经在https://stackoverflow.com/a/61047809/6726766那里回答了-作为私有API的替代,您可以使用https://github.com/AntonPoltoratskyi/NativeUI

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

它看起来完全像本机警报,但是可以配置。

© www.soinside.com 2019 - 2024. All rights reserved.