如何在Swift4上关闭UIView

时间:2019-03-14 14:26:02

标签: ios swift uiview uikit uigesturerecognizer

我有一个UIView,每次我在另一个视图中按一个按钮时都会显示

@IBOutlet weak var view1: UIView!
@IBOutlet weak var view2: UIView! 

@IBAction func showView(_ sender: Any) {
    view2.isHidden = false
}

我想要添加一个轻击手势,该手势允许我每次在视图外部单击时都隐藏view2,并且由于这些视图是可拖动的,因此我希望第二个视图在隐藏时不可被点击(因此,如果我在我看来,我不冒险移动它。 这是我尝试过的:

  1. 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!)
        }
    
    }
    
  2. let closeTapGesture = UITapGestureRecognizer(target: view, action: #selector(getter: view2.isHidden)
        view.addGestureRecognizer(closeTapGesture)
    

没有一项工作,我该怎么办?

2 个答案:

答案 0 :(得分:1)

您的轻击手势只能处理closeView。

@objc func closeView() {
        view2.isHidden = true
        view2.isUserInteractionEnabled = false
        gesture?.isEnabled = false
    }

然后单击显示您的view2的按钮应调用此按钮。

func  showView() {
    view2.isHidden = false
    view2.isUserInteractionEnabled = true
    gesture?.isEnabled = true
}

答案 1 :(得分:1)

您需要检查是否确实在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
    }