简体   繁体   中英

Dismiss ActionSheet by touch outside of it in iPhone

I want to dismiss UIActionsheet when user taps anywhere else on screen. I don't want to provide cancel button.

My code

UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:sheetTitle delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];

    [sheet setTag:indexPath.row];

    for (NSString *buttonTitle in buttonTitles)
    {
        [sheet addButtonWithTitle:buttonTitle];
    }

    [sheet showFromToolbar:self.navigationController.toolbar];

    [sheet release];
    [buttonTitles release];

Make your ActionSheet object global and then allocate it into your block. then you can dismiss it from outside touches event on your view. add following block into your view.

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
  [sheet removeFromSuperView];
  sheet=nil;
}

hope this will help you

try this

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOut:)];
tap.cancelsTouchesInView = NO;
[actionSheet.window addGestureRecognizer:tap];
[tap release];`<br> `-(void)tapOut:(UIGestureRecognizer *)gestureRecognizer {
CGPoint p = [gestureRecognizer locationInView:self.actionSheet];

if (p.y < 0) {
  [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}
}

It is UIActionsheet default feature to dismiss when touch outside . No Need of additional code.

[sheet showFromToolbar:self.navigationController.toolbar];

is making the problem I think. Change it to

[sheet showInView:[UIApplication sharedApplication].keyWindow];

Declare ActionSheet globally and then paste this code after the viewdidload

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

        [super touchesBegan:touches withEvent:event];
        [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
    }

works 100%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM