Search code examples
iosswiftviewuigesturerecognizertap

How to remove popView if we tap anywhere in the background except tapping in popView in swift


I have created one popView with textfield and button in ViewController. if i click button then popView is appearing, and i am able to enter text in textfield and submit is working, and if i tap anywhere in view also i am able to remove popView, but here i want if i tap on anywhere in popView i don't want to dismiss popView, Please help me in the code.

here is my code:

 import UIKit

 class PopUPViewController: UIViewController {

@IBOutlet weak var popView: UIView!
@IBOutlet weak var inputField: UITextField!
@IBOutlet weak var textLabel: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
    popView.isHidden = true
    // Do any additional setup after loading the view.
}

@IBAction func butnAct(_ sender: Any) {
    view?.backgroundColor = UIColor(white: 1, alpha: 0.9)
    popView.isHidden = false
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PopUPViewController.dismissView))
    view.addGestureRecognizer(tap)
}

@objc func dismissView() {
    self.popView.isHidden = true
    view?.backgroundColor = .white
}

@IBAction func sendButton(_ sender: Any) {
    self.textLabel.text = inputField.text
}
}

In my code if i tap anywhere in the view popView is removing even if i tap on popView also its removing, i don't need that, if i tap on popView then popView need not to be remove.

Please help me in the code


Solution

  • You can override the touchesBegan method which is triggered when a new touch is detected in a view or window. By using this method you can check a specific view is touched or not.

    Try like this

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
         let touch = touches.first
         if touch?.view != self.popView {
            dismissView()
        }
    }
    
    func dismissView() {
        self.popView.isHidden = true
        view?.backgroundColor = .white
    }