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

You can use touchesBegan method for that:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    self.helpView.isHidden = true
}

Swift 5.1:

This should help to dismiss the view once touched outside of the view.

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
    {
        let touch = touches.first
        if touch?.view != self.yourView
        { self.dismiss(animated: true, completion: nil) }
    }

In Swift 4

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
     let touch = touches.first
     if touch?.view == self.view {
        commentsTxtView.resignFirstResponder()
    }
}

In touch began you should write like

override func touchesBegan(_ touches: Set<AnyHashable>, 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
    }
}

Tags:

Ios

Uiview

Swift