把这个放在你的UIViewController
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if (touch.view!=yourView && yourView) {
[yourView removeFromSuperview];
yourView=nil;
}
}
编辑:仅在视图存在时才检测触摸和移除的更改
EDIT2:您可以将以下内容添加到您的 UIButtons/UITableView 方法中
if (yourView) {
[yourView removeFromSuperview];
yourView=nil;
}
或将 touchesBegan:withEvent: 作为 touchDown 事件添加到您的按钮。
这很烦人,但看不到其他方法,因为 touchesBegan 方法不会被交互式元素调用。
EDIT3:正确的废话,认为我已经搞定了
在您的界面中添加UIGestureRecognizerDelegate
@interface ViewController : UIViewController <UIGestureRecognizerDelegate> {
然后在你的viewDidLoad 添加这个
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMethod)];
tapped.delegate=self;
tapped.numberOfTapsRequired = 1;
[self.view addGestureRecognizer:tapped];
然后在你的 viewController 中添加这两个方法
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if (touch.view!=yourView && yourView) {
return YES;
}
return NO;
}
-(void)tapMethod {
[yourView removeFromSuperview];
yourView=nil;
}