Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to choose order of buttons in UIAlertController

I was under the impression that if the normal action is a destructive action and the other is a cancel action in their UIAlertController that the destructive one should be on the left and the cancel should be on the right.

If the normal action is not destructive, then the normal action should be on the right and the cancel should be on the left.

That said, I have the following:

var confirmLeaveAlert = UIAlertController(title: "Leave", message: "Are you sure you want to leave?", preferredStyle: .Alert)

let leaveAction = UIAlertAction(title: "Leave", style: .Destructive, handler: {
        (alert: UIAlertAction!) in

        //Handle leave

    }
)

let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)

confirmLeaveAlert.addAction(leaveAction)
confirmLeaveAlert.addAction(cancelAction)

self.presentViewController(confirmLeaveAlert, animated: true, completion: nil)

I was under the impression that if I add the leaveAction first, then the cancelAction that the leaveAction would be the button on the left. This was not the case. I tried adding the buttons in the opposite order as well and it also resulted in the buttons being added in the same order.

Am I wrong? Is there no way to achieve this?

like image 880
David Avatar asked Aug 27 '15 22:08

David


2 Answers

My solution to this was to use the .Default style instead of .Cancel for the cancelAction.

like image 73
Eric Aya Avatar answered Nov 07 '22 05:11

Eric Aya


Since iOS9 there is a preferredAction property on UIAlertController. It places action on right side. From docs:

When you specify a preferred action, the alert controller highlights the text of that action to give it emphasis. (If the alert also contains a cancel button, the preferred action receives the highlighting instead of the cancel button.)

The action object you assign to this property must have already been added to the alert controller’s list of actions. Assigning an object to this property before adding it with the addAction: method is a programmer error.

like image 30
nemissm Avatar answered Nov 07 '22 05:11

nemissm