IOS - How to hide a view by touching anywhere outside of it

后端 未结 12 1586
温柔的废话
温柔的废话 2020-12-29 23:23

I\'m new to IOS programming, I\'m displaying a view when a button is clicked, using the following code inside the button method.

 @IBAction func moreButton(_         


        
12条回答
  •  萌比男神i
    2020-12-29 23:42

    You can achieve what you want doing the following (tested with Swift 4.1 and 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
    

    If you want to keep the gesture recognizer (maybe because you open helpView more than once) change dismissView to this version:

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

    That's all...!

提交回复
热议问题