如何向UIActionSheet添加手势?

时间:2015-08-10 03:40:04

标签: ios uiactionsheet

在iOS8中,我想向UIActionSheet添加一个手势,以便在点击背景时关闭ActionSheet。但actionsheet.frame为(0,0,0,0),addGestureRecognizer不起作用,addSubview也不起作用。

2 个答案:

答案 0 :(得分:0)

我认为你可以这样做,

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClicked:)];
[self.actionSheet.window addGestureRecognizer:tap];

然后您可以检测到alertView

外侧的点击
-(void)tapClicked:(UIGestureRecognizer *)gestureRecognizer {
    CGPoint fr = [gestureRecognizer locationInView:self];
    if (fr.y < 0) { // outside Tap
         [self dismissWithClickedButtonIndex:0 animated:YES]; // alertview dismiss method
    }
 }

答案 1 :(得分:0)

您应该将UIGestureRecognizer添加到背景视图而不是UIActionSheet本身。我做了一个示例项目,效果很好。

#import "ViewController.h"
@interface ViewController () <UIActionSheetDelegate>
// make the UIActionSheet to be a property so that you can track it
@property (nonatomic, strong) UIActionSheet *actionSheet;
@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  _actionSheet = [[UIActionSheet alloc] initWithTitle:@"Action Sheet" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Some button" otherButtonTitles:nil];
  _actionSheet.actionSheetStyle = UIActionSheetStyleAutomatic;

  UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap)];
  // add the gestureRecognizer to the background view
  [self.view addGestureRecognizer:singleTap];
}

- (void)singleTap {
  // check nil & visible
  if (_actionSheet && _actionSheet.isVisible) {
    // dismiss with cancel button
    [_actionSheet dismissWithClickedButtonIndex:0 animated:YES];
  }
}

// I pulled out a UIButton to show the UIActionSheet
- (IBAction)showActionSheet:(UIButton *)sender {
  [_actionSheet showInView:self.view];
}