mcfly soft
mcfly soft

Reputation: 11645

how to color specific words in a uialertview or UIAlertController ? (SWIFT)

is there a way to color some specific words in uialertview ? I mean, can I color the word RED as red and at the same time GREEN as green ?

enter image description here

Can someone bring me on the right way?

Upvotes: 0

Views: 6981

Answers (2)

Anton
Anton

Reputation: 450

I already answered there https://stackoverflow.com/a/61047809/6726766 - as an alternative to private API you could use https://github.com/AntonPoltoratskyi/NativeUI

pod 'NativeUI/Alert', '~> 1.0'

It looks exactly like native alert, but configurable enough.

Upvotes: 0

Teo
Teo

Reputation: 3442

You could make use of NSAttributedString and UIAlertController:

    let strings = [["text" : "My String red\n", "color" : UIColor.redColor()], ["text" : "My string green", "color" : UIColor.greenColor()]];

    var attributedString = NSMutableAttributedString()

    for configDict in strings {
        if let color = configDict["color"] as? UIColor, text = configDict["text"] as? String {
            attributedString.appendAttributedString(NSAttributedString(string: text, attributes: [NSForegroundColorAttributeName : color]))
        }
    }

    let alert = UIAlertController(title: "Title", message: "", preferredStyle: .Alert)

    alert.setValue(attributedString, forKey: "attributedMessage")

    let cancelAction = UIAlertAction(title: "Cancel",
        style: .Default) { (action: UIAlertAction!) -> Void in
    }

    presentViewController(alert,
        animated: true,
        completion: nil)

You use the key attributedMessage to assign an attributed string for the message and the key attributedTitle for the title.

I couldn't find a solution for UIAlertView that works but all of them use private variables which is not good practice. You should know that UIAlertView is deprecate from iOS 8 on, so if you are not targeting lower, you should not use it, instead use UIAlertController

Upvotes: 15

Related Questions