Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

uiview

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(_ sender: Any)
    {
        self.helpView.isHidden = false
    }

initially, the self.helpView.isHidden is set to true in viewDidLoad method to hide the view. Now, how can i dismiss this view by touching anywhere outside the view. From the research, i found that, it can be done by creating a transparent button that fits the whole viewController. So then by clicking on the button, we can make the view to dismiss. Can anyone give me the code in swift 3 to create such button.

Or, if there is any other better way to hide a view, it is welcomed.

I'm using Xcode 8.2, swift 3.0

Thanks in advance.

like image 406
Tester Avatar asked Feb 22 '17 07:02

Tester


3 Answers

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
    }
}
like image 104
Lakshmi Keerthana Siddu Avatar answered Nov 09 '22 09:11

Lakshmi Keerthana Siddu


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) }
    }
like image 39
Santhosh Umapathi Avatar answered Nov 09 '22 10:11

Santhosh Umapathi


In Swift 4

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
     let touch = touches.first
     if touch?.view == self.view {
        commentsTxtView.resignFirstResponder()
    }
}
like image 9
Hanny Avatar answered Nov 09 '22 08:11

Hanny