Manoj Manoj - 5 months ago 52
iOS Question

UIalertcontroller sequence of buttons

I would like to change the sequence of alert action button, as per code I tried all possibility but it is not allowed me to change the sequence.

As per HIG, cancel is on right hand side
https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/Alerts.html#//apple_ref/doc/uid/TP40006556-CH14-SW1

See my code here

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"alert" message:@"My alert message" preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction* noButton = [UIAlertAction
actionWithTitle:@"Cancel"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * action)
{
[alertController dismissViewControllerAnimated:YES completion:nil];
}];

UIAlertAction* yesButton = [UIAlertAction
actionWithTitle:@"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{

[alertController dismissViewControllerAnimated:YES completion:nil];

}];


[alertController addAction:yesButton];
[alertController addAction:noButton];
[self presentViewController:alertController animated:YES completion:nil];


this will give me following result. I want to change Cancel
button
on right hand and OK
button
on left hand side.

enter image description here

I appreciate for your time.

Answer

Change the action style for cancel button type to UIAlertActionStyleDefault instead of UIAlertActionStyleCancel

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"alert" message:@"My alert message" preferredStyle:UIAlertControllerStyleAlert];


UIAlertAction* yesButton = [UIAlertAction
                            actionWithTitle:@"OK"
                            style:UIAlertActionStyleDefault
                            handler:^(UIAlertAction * action)
                            {

                                [alertController dismissViewControllerAnimated:YES completion:nil];

                            }];

UIAlertAction* noButton = [UIAlertAction
                           actionWithTitle:@"Cancel"
                           style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction * action)
                           {
                               [alertController dismissViewControllerAnimated:YES completion:nil];
                           }];

[alertController addAction:yesButton];
[alertController addAction:noButton];


[self presentViewController:alertController animated:YES completion:nil];

And now you can change the order of the buttons by simply changing the positions of

 [alertController addAction:yesButton]; //If you yesButton to appear first (left)
 [alertController addAction:noButton];

The UIAlertActions are flexible enough to reorder. They are not fixed .