Search code examples
iosobjective-cxcode7uiactionsheet

UIActionSheet Cancel button is not working properly


UIActionSheet , it has buttons with title ,I am fetching the title from the array .I want to get the buttons title and displaying in UILabel, that i did , but if I press cancel button the cancel buttons also displaying ,I dont want to display the cancel button title in UILabel the below code which i have tried ,

 - (IBAction)site_Selection:(id)sender {

NSArray *array = @[@"one",@"two",@"three",@"Smart Gladiator1"];

UIActionSheet *actionSheet = [[UIActionSheet alloc]
                              initWithTitle:nil
                              delegate:self
                              cancelButtonTitle:nil
                              destructiveButtonTitle:nil
                              otherButtonTitles:nil];
actionSheet.delegate = self;
for (NSString *title in array) {
    [actionSheet addButtonWithTitle:title];
}

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


[actionSheet showInView:self.view];


   }

     -(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];


self.btn_site_selection.titleLabel.text =  [actionSheet buttonTitleAtIndex:buttonIndex];

 }

Please help me to do this ,


Solution

  • You should not handle the cancel button press.

    Since all button presses on UIActionSheet are handled by actionSheet:clickedButtonAtIndex: you will need to check if the button index is that of the cancel button. You can do this with the cancelButtonIndex on UIActionSheet:

    - (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
        if  (actionSheet.cancelButtonIndex == buttonIndex) {
            return;
        }
    
    }