本文介绍了如何更改一行中单个字母或一个单词的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to change color of word in "message" in AlertView

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

很抱歉,如果问题不正确.

Sorry if question is not correct.

推荐答案

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

As I've written in my comment above, UIAlertView is deprecated, so you'll have to use UIAlertController instead. You can, however, set attributed strings for the message, using (non-swifty) key-value coding (since UIAlertView is a subclass of NSObject): setting an attributed string for key "attributedMessage". The associated key for the title is "attributedTitle".

但是,请注意,这些功能似乎-据我所知--未由Apple记录,仅由用户通过运行时自省.

Note, however, that these features seems---as far as I can find---undocumented by Apple, referenced only as derived by users via 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)
    }
}

产生以下结果:

这篇关于如何更改一行中单个字母或一个单词的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 00:43