Action sheet cancel button not cancelling action sheet

509 Views Asked by At

I am passing an array(which is coming from database) to action sheet. I have added cancel button but it is not cancelling.It is showing error array beyond bounds. Here is my code:

UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"Chatting Apps" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];

    for (int i =0;i<self.arrOfAppNames.count;i++) {

        [actionSheet addButtonWithTitle:[[self.arrOfAppNames objectAtIndex:i]objectAtIndex:1]];

    }
    [actionSheet addButtonWithTitle:@"Cancel"];
    actionSheet.cancelButtonIndex = [self.arrOfAppNames count];
    [actionSheet showInView:self.view];
2

There are 2 best solutions below

4
BHASKAR On

Use this code hope this helps you:

UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"Chatting Apps" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];

for (int i =0;i<self.arrOfAppNames.count;i++) {

    [actionSheet addButtonWithTitle:[[self.arrOfAppNames objectAtIndex:i]objectAtIndex:1]];

}
[actionSheet addButtonWithTitle:@"Cancel"];
actionSheet.cancelButtonIndex = (int)[self.arrOfAppNames count];
[actionSheet showInView:self.view];
2
dopl On

This is what works for me when I add a Cancel button to an action sheet:

[actionSheet addButtonWithTitle:@"Cancel"];
actionSheet.cancelButtonIndex = actionSheet.numberOfButtons - 1;