Dismiss keyboard on touch anywhere outside UITextField

前端 未结 8 1814
梦毁少年i
梦毁少年i 2020-11-27 17:22

I am developing an iPad app that has a large number of UIViewControllers, UITableViews (with cells with accessoryViews of UIText

相关标签:
8条回答
  • 2020-11-27 17:51

    May be I don't understands what you want properly but - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch method may help you for dismissing the keyboard

    0 讨论(0)
  • 2020-11-27 17:52

    To resign the current first responder, I tried using endEditing, but had some issues setting a first responder afterwards. I then used a recursive method for awhile to find the first responder in a UIView category method:

    - (UIView *)getFirstResponder {
    
        if (self.isFirstResponder) {
            return self;
        }
    
        for (UIView *subView in self.subviews) {
            UIView *firstResponder = [subView getFirstResponder];
    
            if (firstResponder != nil) {
                return firstResponder;
            }
        }
    
        return nil;
    }
    

    Once the responder is returned, then I can just call resignFirstResponder on it.

    Just today though, a buddy of mine at work showed me an even better way here: http://overooped.com/post/28510603744/i-had-completely-forgotten-about-nil-targeted

    Just call this:

    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    

    Awesome one liner!

    0 讨论(0)
提交回复
热议问题