ios - 如何更改一行中单个字母或一个单词的颜色

标签 ios swift swift2 xcode7

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

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

抱歉,如果问题不正确。

最佳答案

正如我在上面的评论中所写,UIAlertView 已被弃用,因此您必须改用 UIAlertController。但是,您可以为消息设置属性字符串,使用(非快速的)键值编码(因为 UIAlertViewNSObject 的子类>): 为键 "attributedMessage" 设置属性字符串。标题的关联键是 "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)
    }
}

产生以下结果:

enter image description here

关于ios - 如何更改一行中单个字母或一个单词的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35141400/

相关文章:

iphone - 使用铃声作为 iOS 的自定义推送通知声音

ios - Swift - 在没有推送通知的情况下启动应用程序

ios - 在swift中遍历nsdictionary

ios - 自定义按钮的初始化程序

objective-c - 当 XML 为空时,xcode 崩溃 - 可以插入虚拟对象吗?

ios - Firebase 获取数据

ios - Collection View 更改间距

ios - 如何在 Swift 2 中模糊场景

ios - 必须调用父类(super class) 'UITableViewHeaderFooterView' 的指定初始化程序

swift2 - 如何在映射中抛出错误以将字符串转换为整数数组以获取数字格式异常