如何跟踪自定义视图外的点击

How to track clicks outside the custom view

我有一个自定义视图,看起来是这样

如何跟踪白色 space(视图外)的点击并将其隐藏?

您可以在覆盖整个屏幕的自定义视图下添加一个UIView,给它一个0.1左右的alpha。然后,您可以向其添加 tapGestureRecognizer 以捕获自定义视图之外的所有触摸。

记得在隐藏自定义视图时也隐藏叠加层,这样以后触摸就不会被阻止了。

你可以使用 touchesBegan 来跟踪它:

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch= [touches anyObject];
    if ([touch view] == self.view)
    {
        // do stuff
    }
}

对于swift:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if let touch = touches.first {
            if touch.view == self.view {
                // do stuff
            }
        }
        super.touchesBegan(touches, withEvent:event)
    }