In iOS8 ,I want to add a gesture to an UIActionSheet
so I can close the ActionSheet when I tap on background. but actionsheet.frame is (0,0,0,0),addGestureRecognizer doesn't work,addSubview neither.
Asked
Active
Viewed 281 times
-1

Mayank Patel
- 3,868
- 10
- 36
- 59

cyfeelm
- 1
- 2
2 Answers
0
I think you can do like this way,
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClicked:)];
[self.actionSheet.window addGestureRecognizer:tap];
then after you can detect tap on out side of alertView
-(void)tapClicked:(UIGestureRecognizer *)gestureRecognizer {
CGPoint fr = [gestureRecognizer locationInView:self];
if (fr.y < 0) { // outside Tap
[self dismissWithClickedButtonIndex:0 animated:YES]; // alertview dismiss method
}
}

Mayank Patel
- 3,868
- 10
- 36
- 59
-
sorry,I didn't describe my problem properly.I set the "cancelButtonTitle" to nil,So it won't didmiss when I click on the background. Now I've solved the problem by set cancelButtonTitle to something , there is no need to add any other code. thanks for your help,anyway. – cyfeelm Aug 10 '15 at 07:08
0
You should add the UIGestureRecognizer to the background view rather than the UIActionSheet itself. I've made a sample project, and it works well.
#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];
}

haopeng
- 243
- 1
- 8
-
sorry,I didn't describe my problem properly.I set the "cancelButtonTitle" to nil,So it won't didmiss when I click on the background. Now I've solved the problem by set cancelButtonTitle to something , there is no need to add any other code – cyfeelm Aug 10 '15 at 07:07