Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the color of cancel button in UIAlertController with preferredStyle: .ActionSheet

Is it possible to change the color of cancel button to red , i know we can by using Destructive style

  let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .Destructive) { action -> Void in
            print("Cancel")
        }

but i want the cancel button separately , like this enter image description here

like image 475
bikram sapkota Avatar asked Sep 01 '16 09:09

bikram sapkota


4 Answers

This is code of how to make the alert like you said:

let alert = UIAlertController(title: "Hello", message: "Hello World", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Open in Google Maps", style: . default, handler: nil))
alert.addAction(UIAlertAction(title: "Open in Google", style: . default, handler: nil))
alert.addAction(UIAlertAction(title: "Copy Address", style: . default, handler: nil))

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

You have to use 2 kind of style. In here, I used .destructive and .default, It will separate alert action into 2 part

like image 21
Nguyễn Anh Việt Avatar answered Nov 05 '22 10:11

Nguyễn Anh Việt


let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) 
cancelAction.setValue(UIColor.red, forKey: "titleTextColor")
like image 53
Igor Avatar answered Nov 05 '22 09:11

Igor


Swift 4

You can change the color of the alert action button using the below code.

let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
cancelAction.setValue(UIColor.red, forKey: "titleTextColor")

Hope this helps you.

like image 35
Vinoth Vino Avatar answered Nov 05 '22 11:11

Vinoth Vino


Swift4.2

If you have multiple UIAlertAction, then add "Cancel" UIAlertAction in UIAlertController like that.

 let alert = UIAlertController(title: "Title", message: "Your Message", preferredStyle: UIAlertController.Style.actionSheet)
 alert.addAction(UIAlertAction(title: "first",style: .default, handler: { action in
     //Do something....           
   }))
 alert.addAction(UIAlertAction(title: "second", style: .default, handler: { action in
     //Do something....           
   }))
// Add cancel UIAlertAction
 let cancelAlert = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
     cancelAlert.setValue(UIColor.red, forKey: "titleTextColor")
     alert.addAction(cancelAction).  
     self.present(alert, animated: true, completion: nil)
like image 20
Sukh Avatar answered Nov 05 '22 09:11

Sukh