如何改变单个字母或一个单词的颜色
如何在AlertView中更改“消息”中的单词颜色
@@IBAction func btn_instructions(sender: UIButton) { let alertView = UNAlertView(title: "MyTitle", message: "Here green text, here red text") alertView.show()
对不起,如果问题不正确。
正如我在上面的评论中所写, UIAlertView
已被弃用,因此您必须使用UIAlertController
。 但是,您可以使用(非swifty)键值编码设置消息的属性字符串(因为UIAlertView
是NSObject
的子类):为键"attributedMessage"
设置属性字符串。 标题的关联键是"attributedTitle"
。
但请注意,这些function似乎 – 据我所知 – 没有Apple记录,只能由用户通过运行时内省来引用。
以下是一个例子:
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) } }
产生以下结果:
UIAlertController无法实现这一点(UIAlertView已弃用)。 UIAlertController接受title
和message
参数的可选字符串(请参阅Apple在UIAlertController上的文档 )。
为了在一行文本中使用多种颜色,您需要使用NSAttributedString
(这是一个很好的NSAttributedString教程 )。
由于String不能保存任何属性,因此您将无法在UIAlertController上使用NSAttributedString。 您必须使用NSAttributedString标签创建自己的模态ViewController,以显示您要求的内容。