[英]How to dismiss UIView on tap Swift4
I have a UIView
that is showed every time I press a button in another view 我有一个UIView
,每次我在另一个视图中按一个按钮时都会显示
@IBOutlet weak var view1: UIView!
@IBOutlet weak var view2: UIView!
@IBAction func showView(_ sender: Any) {
view2.isHidden = false
}
What I want is to add a tap gesture that allows me to hide view2 every time I tap outside of the view and, since those views are draggable, I want the second view not to be tappable when hidden ( so that if I touch under my view I don't risk to move it. This is what I tried: 我想要添加一个轻击手势,使我每次在视图外部轻按时都可以隐藏view2,并且由于这些视图是可拖动的,因此我希望第二个视图在隐藏时不被轻按(这样,如果我在视图,我不冒险移动它。这是我尝试的方法:
var gesture : UITapGestureRecognizer? override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(closeView), name: NSNotification.Name("CloseView"), object: nil) gesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.closeView)) } @objc func closeView() { if view2.isHidden == false { view2.isUserInteractionEnabled = true view2.isHidden = false self.view.removeGestureRecognizer(gesture!) } else { view2.isHidden = true view2.isUserInteractionEnabled = true self.view.addGestureRecognizer(gesture!) } }
let closeTapGesture = UITapGestureRecognizer(target: view, action: #selector(getter: view2.isHidden) view.addGestureRecognizer(closeTapGesture)
None of this work, how can I do? 没有这项工作,我该怎么办?
Your tap gesture should only handle closeView . 您的轻击手势只能处理closeView。
@objc func closeView() {
view2.isHidden = true
view2.isUserInteractionEnabled = false
gesture?.isEnabled = false
}
And the the button click to show your view2 should call this. 然后单击按钮以显示您的view2应该调用此按钮。
func showView() {
view2.isHidden = false
view2.isUserInteractionEnabled = true
gesture?.isEnabled = true
}
You need to check if you actually tapped outside of view2: 您需要检查是否确实在view2之外点击了:
var gesture : UITapGestureRecognizer?
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(closeView), name: NSNotification.Name("CloseView"), object: nil)
let gesture = UITapGestureRecognizer(target: self, action: #selector(closeView(_:)))
view.addGestureRecognizer(gesture)
self.gesture = gesture
}
@objc private func closeView(_ tapGestureRecognizer: UITapGestureRecognizer) {
let location = tapGestureRecognizer.location(in: view2)
guard view2.isHidden == false,
!view2.bounds.contains(location) else { //We need to have tapped outside of view 2
return
}
view2.isHidden = true
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.