28

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.

1
  • The way you read should be good and easy enough to implement, you can also override touchesBegan and check if the touch view is the view or not/ or compare the touch position to hide it
    – Tj3n
    Feb 22, 2017 at 7:49

12 Answers 12

52

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
    }
}
5
  • 1
    Thank you. By doing this, the helpView doesn't dismiss by touching it. as expected.
    – Tester
    Feb 22, 2017 at 10:14
  • May i know the exact issue Feb 22, 2017 at 10:34
  • I want the helpView to dismiss only when we touch outside of that view, not by clicking on that view itself. So, i meant this code works exactly like i expected.
    – Tester
    Feb 22, 2017 at 12:18
  • 1
    for swift 3: touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
    – Savas Adar
    Sep 20, 2017 at 14:26
  • 1
    won't this not work if there's another view outside the view you want to dismiss? Oct 10, 2018 at 17:11
12

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) }
    }
3
  • Hey @Santhosh. I appreciate your answer. It helped!
    – iHarshil
    Mar 16, 2020 at 10:11
  • @iHarshil , Glad it helped. Anytime !! Mar 17, 2020 at 13:45
  • 1
    An alternative version would be touch?.view == defaultView. defaultView is the full screen UIView (Safe Area's parent) that XIB adds by default when you create a new UIViewController (use an outlet to get access). This view is always in the "background", so if you create e.g. a custom popup that doesn't fill the whole screen, "outside" is always that default view.
    – Neph
    Apr 13, 2021 at 14:18
9

In Swift 4

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

You can use touchesBegan method for that:

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

    self.helpView.isHidden = true
}
0
4

Swift

 override func touchesBegan(_ touches: Set<AnyHashable>, withEvent event: UIEvent) {
     var touch: UITouch? = touches.first
     if touch?.view != self.yourView {
         self.yourView.isHidden = true
     }
 }

Objective C

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event  {
     UITouch *touch = [touches anyObject];
     if(touch.view != self.yourView){
         self.yourView.hidden = YES;
     }
 }
1

Inside the moreButton selected, you can do something like this

 @IBAction func moreButton(_ sender: Any)
    {
        self.helpView.isHidden = false
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissView))
        view.addGestureRecognizer(tap)
    }

    func dismissView() {
        self.helpView.isHidden = true
        self.view.removeGestureRecognizer(tap)
    }
3
  • Thanks for the response. By adding this, i get two error. "Use of unresolved identifier 'tap'" and "Type 'UIViewController' has no member 'dismissView'". I'm sure that i have added all codes that you suggested. Is there anything else i have to do ?
    – Tester
    Feb 22, 2017 at 9:31
  • Hi. try typing view.view. I think youve assigned view = ViewController. Feb 22, 2017 at 9:53
  • Also declare the "tap" outside the function. let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissView)) and then put @IBAction func moreButton(_ sender: Any) { self.helpView.isHidden = false view.addGestureRecognizer(tap) } Feb 22, 2017 at 9:54
0

You could create another transparent button or, your base view (assuming it's a single view below the button) can then address what you're trying to do. First, you would need to make it tappable. Then you want to handle the logic for what happens when tapped, or untapped.

0

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...!

0

You can use this method in swift 4.

add the tag number to the uiview you want to add action

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
{
    if touches.first?.view?.tag == 10{
        dismiss(animated: true, completion: nil)
        super.touchesEnded(touches , with: event)
    }
}
0

in my case I followed it by touchesEnded logic,

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if([touch view]== self.UIViewThatNeedsToBeDismissed) {
        NSLog(@"inside view touch");
    } else {
        NSLog(@"release it");
    }
}
0

You can use the below function some this check on the view name will not work but if you have more than one view the problem you will see that if you tap inside your second view the same action will perform. I would prefer to add tapGesture. This is the other solution.

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


}
0
private func addClickToDismiss() {

    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissPresentedView(_:)))
    tapRecognizer.cancelsTouchesInView = false
    presentedViewController.view.superview?.isUserInteractionEnabled = true
    presentedViewController.view.superview?.addGestureRecognizer(tapRecognizer)
}

@objc
private func dismissPresentedView(_ sender: Any?) {
    presentedViewController.dismiss(animated: true)
}

If anyone wants some copy pasta, this is how you do it from a custom UIPresentationController

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.