Unable to choose order of buttons in UIAlertController

孤街浪徒 提交于 2019-11-29 18:50:57

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/32260191/unable-to-choose-order-of-buttons-in-uialertcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!