【问题标题】:How to change color of single letters or one word in line如何更改单个字母或一行单词的颜色
【发布时间】:2016-02-01 22:13:02
【问题描述】:

如何在 AlertView 中更改“消息”中单词的颜色

@@IBAction func btn_instructions(sender: UIButton) {
    let alertView = UNAlertView(title: "MyTitle", message: "Here green text, here red text")
 alertView.show()

如果问题不正确,请见谅。

【问题讨论】:

  • 请注意 UIAlertView 在 iOS9 中已被弃用(我假设上面的 UNAlertView 是一个错字)。您应该改用UIAlertController
  • @LeoDabus 实际上,它确实具有属性文本属性,"attributedTitle""attributedMessage" 分别用于标题和消息文本。但是,据我所知,Apple 没有记录这些内容;我只能通过runtime introspection 找到用户引用的它们。
  • UIAlertAction 是否也有“attributedTitle”?

标签: ios swift swift2 xcode7


【解决方案1】:

正如我在上面的评论中所写,UIAlertView 已被弃用,因此您必须改用UIAlertController。但是,您可以为消息设置属性字符串,使用(非 swifty)键值编码(因为 UIAlertViewNSObject 的子类):为键 @ 设置属性字符串987654328@。标题的关联键是"attributedTitle"

但请注意,据我所知,这些功能似乎没有被 Apple 记录在案,仅由用户通过 runtime introspection 派生引用。

下面是一个例子:

import UIKit

class ViewController: UIViewController {

    // ...

    @IBAction func showAlert(sender: UIButton) {

        let alertController = UIAlertController(title: "Foo", message: "", preferredStyle: UIAlertControllerStyle.Alert)

        /* attributed string for alertController message */
        let attributedString = NSMutableAttributedString(string: "Bar Bar Bar!")

        attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(),
            range: NSRange(location:0,length:3))
        attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(),
            range: NSRange(location:4,length:3))
        attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(),
            range: NSRange(location:8,length:3))

        alertController.setValue(attributedString, forKey: "attributedMessage")

        /* action: OK */
        alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        self.presentViewController(alertController, animated: true, completion: nil)
    }
}

产生以下结果:

【讨论】:

  • UIAlertAction 也有“attributedTitle”吗?我想指定 Actions 的字体和大小。
【解决方案2】:

这对于 UIAlertController 是不可能的(UIAlertView 已弃用)。 UIAlertController 接受titlemessage 参数的可选字符串(请参阅Apple's Documentation on UIAlertController)。

为了在一行文本中使用多种颜色,您需要使用NSAttributedString(这是一个很好的NSAttributedString Tutorial)。

由于 String 不能包含任何属性,您将无法在 UIAlertController 上使用 NSAttributedString。您必须使用 NSAttributedString 标签创建自己的模态 ViewController 才能显示您的要求。

【讨论】:

  • 您实际上可以为UIAlertController 使用属性字符串,利用KVC 和密钥attributedMessage
猜你喜欢
  • 2014-11-26
  • 2017-02-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多