How to change color of single letters or one word in line

旧巷老猫 提交于 2020-01-24 13:11:06

问题


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.


回答1:


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".

Note, however, that these features seems---as far as I can find---undocumented by Apple, referenced only as derived by users via runtime introspection.

An example follows below:

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)
    }
}

Producing the following result:




回答2:


This is not possible with UIAlertController (UIAlertView is deprecated). UIAlertController accepts an Optional String for the title and message parameters (see Apple's Documentation on UIAlertController).

In order to use multiple colors in a line of text, you'll need to use NSAttributedString (here's a good NSAttributedString Tutorial).

Since String can't hold any attributes, you won't be able to use NSAttributedString on the UIAlertController. You will have to create your own modal ViewController with a NSAttributedString label in order to display what you are asking for.



来源:https://stackoverflow.com/questions/35141400/how-to-change-color-of-single-letters-or-one-word-in-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!