Hiding the Keyboard when losing focus on a UITextView

后端 未结 10 537
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 10:34

So I have a UITextView that I\'m using to allow the user to submit some text.

My problem is, I can\'t seem to figure out how to allow the user to \'Cancel\' by tappi

相关标签:
10条回答
  • 2020-12-04 10:56

    Here is the swift 3 code

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            if textField.isFirstResponder && touch.view != textField {
                textField.resignFirstResponder()
            }
        }
        super.touchesBegan(touches, with: event)
    }
    
    0 讨论(0)
  • 2020-12-04 10:57

    This is an old post, but I was implementing this solution when i found something a lot simpler (maybe it wasn't available back then).

    [self.myTextView endEditing:YES];

    I'm using a UITableView, so I put this line on the didSelectRowAtIndexPath: method. So far, so good...

    0 讨论(0)
  • 2020-12-04 11:00

    Here is a better solution that does not depend upon an outlet and is going to work with any number of UITextField objects in your controller.

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
        UITouch *touch = [[event allTouches] anyObject];
    
        if (![[touch view] isKindOfClass:[UITextField class]]) {
            [self.view endEditing:YES];
        }
        [super touchesBegan:touches withEvent:event];
    }
    
    0 讨论(0)
  • 2020-12-04 11:02

    My way to do it...

    • Add a reference to the TextView in the @interface of your ViewController:

      @property (weak, nonatomic) IBOutlet UITextView *yourTextView;
      
    • Override this method in the @implementation of your ViewController:

      - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
      {
          if ([self.yourTextView isFirstResponder]) {
            [self.yourTextView resignFirstResponder];
          }
      }
      
    0 讨论(0)
提交回复
热议问题