【问题标题】:how to color specific words in a uialertview or UIAlertController ? (SWIFT)如何为 uialertview 或 UIAlertController 中的特定单词着色? (迅速)
【发布时间】:2015-06-05 08:23:15
【问题描述】:

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

有人可以带我走正确的路吗?

【问题讨论】:

  • 一般来说,你会使用 NSAttributedString,但我不认为 UIAlertViews 可以使用它,但 UIAlertController 可以使用:stackoverflow.com/questions/26460706/…
  • @luk2302 哈哈,什么?您在告诉 skyddict 他不是在询问控制器之前发表了此评论?
  • @Fogmeister 是的!因为当时它只是关于 uialertviews - 我不确定他是否真的了解 uialertcontrollers 以及他所针对的操作系统

标签: ios colors uialertview


【解决方案1】:

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

【讨论】:

  • 然而,他询问的是 UIAlertViews,而不是控制器。
  • UIAlertController 对我来说也可以。但上面的例子只显示了红色文本“红色”。这很好用,但是如何只为特定的单词着色。在我的示例中,我应该有 GREEN -> green 和 RED -> red 这个词。使用mentoined解决方案可以做到这一点吗?
  • @luk2302 for iOS8 UIAlertView 已弃用。如果您的目标是 iOS8,那么您无论如何都不应该使用 UIAlertView。
  • 完美,非常感谢您的努力。那太棒了。我可以在我的 IOS8 环境中使用 UIAlertController。我的 Title 可能会误导 UIAlertView。我还是 OIS 和版本的新手。谢谢!
【解决方案2】:

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

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

它看起来和原生警报一模一样,但也足够可配置。

【讨论】:

    猜你喜欢
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    相关资源
    最近更新 更多