IOS – 如何通过触摸视图外的任何位置来隐藏视图

我是IOS编程的新手,我在单击按钮时显示视图,使用按钮方法中的以下代码。

@IBAction func moreButton(_ sender: Any) { self.helpView.isHidden = false } 

最初,在viewDidLoad方法中将self.helpView.isHidden设置为true以隐藏视图。 现在,我如何通过触摸视图外的任何位置来关闭此视图。 从研究中我发现,可以通过创建适合整个viewController的透明按钮来完成。 因此,通过单击按钮,我们可以使视图解散。 谁能给我swift 3中的代码来创建这样的按钮。

或者,如果有任何其他更好的方法来隐藏视图,欢迎它。

我正在使用Xcode 8.2,swift 3.0

提前致谢。

在触摸开始你应该写得像

 override func touchesBegan(_ touches: Set, withEvent event: UIEvent) { var touch: UITouch? = touches.first //location is relative to the current view // do something with the touched point if touch?.view != yourView { yourView.isHidden = true } } 

您可以使用touchesBegan方法:

 override func touchesBegan(_ touches: Set, with event: UIEvent?) { self.helpView.isHidden = true } 

在选择的moreButton中,你可以做这样的事情

  @IBAction func moreButton(_ sender: Any) { self.helpView.isHidden = false let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissView)) view.addGestureRecognizer(tap) } func dismissView() { self.helpView.isHidden = true self.view.removeGestureRecognizer(tap) } 

您可以创建另一个透明按钮,或者您的基本视图(假设它是按钮下方的单个视图)可以解决您尝试执行的操作。 首先,您需要将其设置为可点击。 然后,您希望处理在轻敲或未触发时发生的情况的逻辑。

你可以实现你想做的事情(使用Swift 4.1和Xcode 9.3测试):

 class ViewController: UIViewController { ... private var dismissViewTap: UITapGestureRecognizer? override func viewDidLoad() { super.viewDidLoad() dismissViewTap = UITapGestureRecognizer(target: self, action: #selector(dismissView)) if let tap = dismissViewTap { view.addGestureRecognizer(tap) } // if let } // viewDidLoad @objc private func dismissView() { guard let tap = dismissViewTap else { return } // guard guard helpView.isHidden == false else { return } // guard helpView.isHidden = true view.removeGestureRecognizer(tap) } // dismissView ... } // ViewController 

如果你想保留手势识别器(可能是因为你不止一次打开helpView),请将dismissView更改为此版本:

 ... @objc private func dismissView() { guard helpView.isHidden == false else { return } // guard helpView.isHidden = true } // dismissView ... 

就这样…!

您可以在swift 4中使用此方法。

标签号添加到要添加操作的uiview

 override func touchesEnded(_ touches: Set, with event: UIEvent?) { if touches.first?.view?.tag == 10{ dismiss(animated: true, completion: nil) super.touchesEnded(touches , with: event) } }