2012-03-22 80 views
0

我在UIView中为iPhone创建了一个迷你弹出式菜单,并且我希望用户能够关闭该视图,如果他们除了选择其中一个选项以外执行任何操作。所以,如果用户点击/滑动/捏住屏幕上的任何其他元素,弹出视图应该消失。如何通过用户点击或在其他位置滑动来移除UIView?

但是,我不想检测阻止别的事情发生的手势......例如,下面有一个UITableView,如果我向上或向下滑动,我希望它按预期方式移动以及解散迷你弹出视图。

我应该使用多个手势识别器,还是应该使用touchesBegan,还是有更好的方法?

+0

看到这篇文章http://stackoverflow.com/questions/6078001/how-do-you-detect-touches-in-specific-uiview-when-sliding-finger-across-mutiple – rakeshNS 2012-03-22 17:28:45

回答

2

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; 
} 
+0

所以我必须附上touchesBegan方法到视图控制器?如果是这样,我想我需要以某种方式检查触摸下的元素? – jowie 2012-03-22 16:39:24

+0

这就是他已经用'if(touch.view!= yourView)'做的事情,然后你可以安全的移除你的支撑。 触摸包含触摸的位置。他然后问是否它是在视图内,如果不是,你可以删除它=) – 2012-03-22 17:08:25

+0

谢谢 - 但不幸的是,这似乎只有在视图控制器的区域没有用户交互......在我有'UIButton '和'UITableView','touchesBegan:'消息似乎没有通过。 – jowie 2012-03-22 22:42:39

相关问题