在 iPad 中使用 NavigationController 解除 ModalViewController 当在视图外点击时
Posted
技术标签:
【中文标题】在 iPad 中使用 NavigationController 解除 ModalViewController 当在视图外点击时【英文标题】:Dismiss ModalViewController with NavigationController in iPad When tap outside the view 【发布时间】:2012-05-13 14:00:18 【问题描述】:所以我通常按照这种方式在 ModalViewController 的视图外点击时关闭它
- (void)viewDidAppear:(BOOL)animated
[super viewDidAppear:animated];
if(UIUserInterfaceIdiomPad == UI_USER_INTERFACE_IDIOM())
if(![self.view.window.gestureRecognizers containsObject:recognizer])
recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapBehind:)];
[recognizer setNumberOfTapsRequired:1];
recognizer.cancelsTouchesInView = NO; //So the user can still interact with controls in the modal view
[self.view.window addGestureRecognizer:recognizer];
[recognizer release];
- (void)handleTapBehind:(UITapGestureRecognizer *)sender
if (sender.state == UIGestureRecognizerStateEnded)
CGPoint location = [sender locationInView:nil]; //Passing nil gives us coordinates in the window
//Then we convert the tap's location into the local view's coordinate system, and test to see if it's in or outside. If outside, dismiss the view.
if (![self.view pointInside:[self.view convertPoint:location fromView:self.view.window] withEvent:nil])
[self dismissModalViewControllerAnimated:YES];
[self.view.window removeGestureRecognizer:recognizer];
它与 regular ModalViewController 一起工作得很好。但是现在我有一个 modelViewController,它是一个以“x”viewController 作为根的 NavigationViewController .. 当我使用这种方式并点击导航栏时控制器被解除,或者当我从 x 控制器导航到“y”控制器并想要返回时,当我单击后退按钮时,ModalView 被解除!这对我来说是错误的行为..我只想关闭控制器,以防点击完全在控制器之外(视图区域 + 导航栏区域).. 任何人都可以提供帮助吗?
【问题讨论】:
【参考方案1】:更新您的代码如下:
- (void)handleTapBehind:(UITapGestureRecognizer *)sender
if (sender.state == UIGestureRecognizerStateEnded)
CGPoint flocation = [sender locationInView:nil]; //Passing nil gives us coordinates in the window
//Then we convert the tap's location into the local view's coordinate system, and test to see if it's in or outside. If outside, dismiss the view.
CGPoint tap = [self.view convertPoint:flocation fromView:self.view.window];
CGPoint tapBar = [self.navigationController.navigationBar convertPoint:flocation fromView:self.view.window];
if (![self.view pointInside:tap withEvent:nil] && ![self.navigationController.navigationBar pointInside:tapBar withEvent:nil])
// Remove the recognizer first so it's view.window is valid.
[self.view.window removeGestureRecognizer:sender];
[self dismissModalViewControllerAnimated:YES];
点击 UIBarButtonItem 时从窗口中移除 UITapGestureRecognizer
-(void)viewWillDisappear:(BOOL)animated
[self.view.window removeGestureRecognizer:self.tapOutsideGestureRecognizer];
【讨论】:
以上是关于在 iPad 中使用 NavigationController 解除 ModalViewController 当在视图外点击时的主要内容,如果未能解决你的问题,请参考以下文章
将 iPhone 应用程序转换为 iPad,然后在 iPad 中使用 splitview?