noquart3r
noquart3r

Reputation: 1

Change title color of UIAlertController

I'm new on iOS development.

I'm trying to change the title and message color of a UIAlertController but is not working, the color is not changing.

Here is my code:

let alert = UIAlertController(title: NSLocalizedString("notifications_popup2_title", comment: ""), message: NSLocalizedString("notifications_popup2_message", comment: ""), preferredStyle: UIAlertControllerStyle.actionSheet)

        // Change font of the title and message
        let titleFont:[NSAttributedStringKey : AnyObject] = [ NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue) : UIFont(name: "Flama-Basic", size: 22)!, NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue) : UIColor(hexString: "#2e2e2e")! ]
        let messageFont:[NSAttributedStringKey : AnyObject] = [ NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue) : UIFont(name: "Flama-light", size: 18)!, NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue) : UIColor(hexString: "#2e2e2e")! ]
        let attributedTitle = NSMutableAttributedString(string: NSLocalizedString("notifications_popup2_title", comment: ""), attributes: titleFont)
        let attributedMessage = NSMutableAttributedString(string: NSLocalizedString("notifications_popup2_message", comment: ""), attributes: messageFont)
        alert.setValue(attributedTitle, forKey: "attributedTitle")
        alert.setValue(attributedMessage, forKey: "attributedMessage")

If i change alert style to .alert it is working...

enter image description here

Upvotes: 0

Views: 1765

Answers (1)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119204

Some of the code you used are deprecated like:

NSAttributedStringKey

is now:

NSAttributedString.Key

also you don't need to specify the rawValue. you just need something like:

    let alertController = UIAlertController(title: "title", message: "message", preferredStyle: .alert)
    alertController.setValue(NSAttributedString(string: "title", attributes: [.foregroundColor : UIColor.red]), forKey: "attributedTitle")
    alertController.setValue(NSAttributedString(string: "message", attributes: [.foregroundColor : UIColor.blue]), forKey: "attributedMessage")

Result: Alert

Note that it only works for .alert. .actionSheet title and message is not colorable unlike the .alert

Also be aware that Using private API can cause rejection. But experience shows that only private methods that their name starts with "_" cause rejection from AppStore private method usage detection system.

Also can stop working anytime if apple decides to change it.

The best option you have is to implement a custom alert yourself.

Upvotes: 1

Related Questions