Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change position of cancel button in UIAlertView?

I noticed that when I delete an app from my iPhone home screen, the alert view that appears shows a Delete button on the left and Cancel on the right. However, when I build a delete function within my app using UIAlertView, the buttons only seem to display with Cancel on the left and Delete on the right.

I'd like my app to be consistent with the OS, but I can't figure out how to make the Cancel button appear first. Does anyone know?

UIAlertView *alert = [[UIAlertView alloc] 
                      initWithTitle:@"Delete Song" 
                      message:@"Are you sure you want to delete this song? This will permanently remove it from your database." 
                      delegate:self 
                      cancelButtonTitle:@"Cancel" 
                      otherButtonTitles:@"Delete", nil];

I tried setting alert.cancelButtonIndex = 1, but that had no effect.

like image 562
arlomedia Avatar asked Dec 16 '10 01:12

arlomedia


2 Answers

Ah, I just figured out how to change this. The cancelButtonTitle argument is optional, so you can add a custom button in whatever position you want and then designate that as the cancel button, like this:

UIAlertView *alert = [[UIAlertView alloc] 
                      initWithTitle:@"Delete Song" 
                      message:@"Are you sure you want to delete this song? This will permanently remove it from your database." 
                      delegate:self 
                      cancelButtonTitle:nil
                      otherButtonTitles:@"Delete", @"Cancel", nil];
alert.cancelButtonIndex = 1;

That puts the Delete button the left and the Cancel button on the right and highlights the Cancel button.

like image 197
arlomedia Avatar answered Sep 21 '22 05:09

arlomedia


A possible reason Apple used an alert view on the home screen was because it once asked users to rate the apps they were removing (not anymore). They likely made the Cancel button the lighter-colored one because this was considered a destructive action (deletes an app and its data).

I guess you could reverse the titles (cancelButtonTitle:@"Delete" otherButtonTitles:@"Cancel", nil) and handle clicks on those buttons the other way around (not sure if Apple did the same). That would be a little awkward though; how about using an action sheet instead?

like image 40
BoltClock Avatar answered Sep 22 '22 05:09

BoltClock