通过点击 UIView 外部来关闭 ViewController 中的 UIView

问题描述

我在我的 ViewController 上展示了一个 UIView,它包含一个覆盖整个视图控制器的表视图。我想在 UIView 之外点击时关闭 UIView,但没有找到任何有助于解决问题的方法。这就是我想要做的,它应该可以工作,但即使未显示 UIView,它也不会注册触摸。有人处理过类似的问题吗?

override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
        let touch: UITouch? = touches.first

        if touch?.view != fullSessionView {
            fullSessionView?.removeFromSuperview()
        }
    }

解决方法

首先,我想看看是否有任何内置的 presentation styles 可以为您工作。但是您必须将您的视图嵌入到视图控制器中。

如果您想坚持使用 UIView,您可以尝试将您的 UIView 呈现在覆盖整个屏幕的透明背景 UIView 之上,并将 UIGestureRecognizer 附加到透明背景。

点击背景会触发回调(通过委托、关闭等),然后删除您的视图。

,

您应该始终调用 super,如下所示:

override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
    super.touchesBegan(touches,with: event) /// always call the super

但无论如何,您想看看 fullSessionView 是否包含触摸。因此,与其检查发生触摸的视图,不如检查发生触摸的位置。像这样:

override func touchesBegan(_ touches: Set<UITouch>,with: event)

    let touch = touches.first
    guard let location = touch?.location(in: fullSessionView) else { return }
    if !fullSessionView.frame.contains(location) {

         /// tapped outside fullSessionView
         fullSessionView?.removeFromSuperview()
    }
}
,

您需要使用目标和操作初始化 UITapGestureRecognizer 到您要添加的视图,如下所示:

let tap = UITapGestureRecognizer(target: self,action: #selector(self.handleTap(_:)))
myView.addGestureRecognizer(tap)
Then,you should implement the handler,which will be called each time when a tap event occurs:
@objc func handleTap(_ sender: UITapGestureRecognizer? = nil) {
    self.removefromSuperview() // this will remove added view from parent view
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...