在外部点击iOS 8上关闭模式表单工作表视图

问题描述:

我一直试图在iOS 8的外部点击上忽略模态表单视图而没有运气,
我试过这段代码

I've been trying to dismiss the modal form sheet view on outside tap on iOS 8 with no luck, I've tried this code

UITapGestureRecognizer *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];

- (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]) 
    {
       // Remove the recognizer first so it's view.window is valid.
      [self.view.window removeGestureRecognizer:sender];
      [self dismissModalViewControllerAnimated:YES];
    }
 }
}

但它没有检测到外部视图点击,任何建议?

But it doesn't detect outside view clicks, any suggestions ?

iOS 8中实际上存在两个问题。首先,手势识别不会开始。

There are actually two problems in iOS 8. First, the gesture recognition does not begin.

我通过添加 UIGestureRecognizerDelegate 协议并实施

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer
{
    return YES;
}

另外,不要忘记用

recognizer.delegate = self;

现在手势识别器应识别手势和目标方法( handleTapBehind:)将被调用。

Now the gesture recognizer should recognize gestures and the target method (handleTapBehind:) will be called.

这是iOS 8中的第二个问题: locationInView:如果将 nil 作为视图传递,则似乎不考虑设备方向。相反,传递根视图是有效的。

Here comes the second problem in iOS 8: locationInView: doesn't seem to take the device orientation into account if nil is passed as a view. Instead, passing the root view works.

这是我的目标代码,似乎适用于iOS 7.1和8.0:

Here's my target code that seems to work for iOS 7.1 and 8.0:

if (sender.state == UIGestureRecognizerStateEnded) {
    UIView *rootView = self.view.window.rootViewController.view;
    CGPoint location = [sender locationInView:rootView];
    if (![self.view pointInside:[self.view convertPoint:location fromView:rootView] withEvent:nil]) {
        [self dismissViewControllerAnimated:YES completion:^{
            [self.view.window removeGestureRecognizer:sender];
        }];
    }
}