UIAlertAction with different color button text
Asked Answered
G

2

16

I am trying to create an UIAlertAction that has black color text for the first button and blue for the second. If I change the tint then all go black but i can't change the first button to black without it. Below is my code:

let alert = UIAlertController(title: "", message: "", preferredStyle: .actionSheet)
// alert.view.tintColor = UIColor.black

alert.addAction(UIAlertAction(title: "First", style: .cancel, handler: nil))

alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

self.present(alert, animated: true, completion: nil)
Gynandry answered 14/3, 2017 at 18:8 Comment(3)
I don't think UIAlertController allows for different colors for different buttons except the style given i.e cancel, default etcSunrise
The color is based on the style - .cancel is black, .default is black, and .destructive is red. There's no way to change the color unless you create your own custom UIAlertController.Consumable
Not at all, UIAlertController buttons, like and some other PopUp controllers use colour from ```window.tint`` If you override this color then default colours change to your colour.Gingerly
G
46

I was able to do it by adding this or each color

let cancelAlert = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler:nil)
                cancelAlert.setValue(UIColor.blue, forKey: "titleTextColor")
                alert.addAction(cancelAlert)
Gynandry answered 15/3, 2017 at 18:13 Comment(2)
I used it in objective C , it crashes the application. any suggestion for objective C ???Etom
I haven't tried it out but here are some suggestions for objective c #36662733Gynandry
G
3

For those who are here to just change the color of an action button, you can change the style like for example .destructive for delete button:

 alert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler:{(UIAlertAction) in
Glasshouse answered 22/7, 2017 at 5:5 Comment(1)
This works when the programmer knows the button is going to represent an action that will change or delete data. It turns the action's title color to red, but it should not be used to explicitly change the color of a title. Unless of course, you're expecting it to be red. The best way to change the color of the title is @Gynandry answer. Though, it leaves the chance of Apple changing the string of the key in the future, so be aware of that.Insurrectionary

© 2022 - 2024 — McMap. All rights reserved.