Search code examples
iphoneobjective-ccocoa-touchfirst-responder

iPhone: dismiss keyboard when user touches background


I have read some other articles like here and here but unfortunately there are some differences in my code that won't make these work (so please don't suggest these answers).

I would like to dismiss the keyboard when the user taps the background. Normally this would be easy, except that my UITextField objects are inside a UIScrollView which makes it so I can't catch the touch events (the UIScrollView swallows them so they don't reach the base view). One way to get around this is to register for a generic gesture (a tap), but this catches all taps, including the ones intended for the submit button.

So basically, 'touchesBegan:withEvent:' wont work because it never gets called, and gestures wont work because they dont account for button presses.

Here's the question: is there some way to detect a simple tap on a UIScrollView? Once I detect the tap I know how to do the rest. Thanks!


Solution

  • You can't use touchesBegan:withEvent on the superview of the scrollview, but what about subclassing UIScrollView and handling the touch there? You can then proceed normally with a call to super's implementation to keep from stepping on the UIScrollView's toes:

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
        /* Insert code to dismiss keyboard if needed */
    
        // This makes sure scrolling proceeds normally.
        [super touchesBegain:touches withEvent:event];
    }