如何在AlertView中的“消息”中更改单词的颜色
@@IBAction func btn_instructions(sender: UIButton) {
let alertView = UNAlertView(title: "MyTitle", message: "Here green text, here red text")
alertView.show()
抱歉,如果问题不正确。
正如我在上面的评论中所写,UIAlertView
不推荐使用,因此您必须改为使用UIAlertController
。但是,您可以使用(非敏捷)键值编码(因为UIAlertView
是的子类NSObject
)来设置消息的属性字符串:为key设置属性字符串"attributedMessage"
。标题的关联键为"attributedTitle"
。
但是请注意,据我所知,这些功能似乎没有被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)
}
}
产生以下结果:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句