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

后端 未结 12 1517
温柔的废话
温柔的废话 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条回答
  • 2020-12-29 23:50

    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) }
        }
    
    0 讨论(0)
  • 2020-12-29 23:50

    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 讨论(0)
  • 2020-12-29 23:54

    You can use touchesBegan method for that:

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    
        self.helpView.isHidden = true
    }
    
    0 讨论(0)
  • 2020-12-29 23:58

    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 讨论(0)
  • 2020-12-30 00:06

    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;
         }
     }
    
    0 讨论(0)
  • 2020-12-30 00:09

    In Swift 4

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
         let touch = touches.first
         if touch?.view == self.view {
            commentsTxtView.resignFirstResponder()
        }
    }
    
    0 讨论(0)
提交回复
热议问题