1

(I'm targetting iOS 2.0 for the time being.)

I have a class which subclasses UITextField and implements the UITextFieldDelegate protocol.

At first, I did not set the class as its own delegate, and when I clicked in the field, the keyboard popped up automatically. So far, so good.

I send the setReturnKeyType: message with UIReturnKeyDone, so it changes the bottom-right button to say Done.

The problem was, when I clicked Done or pressed [Return], nothing happened - the keyboard wouldn't go away.

I tried adding self as an observer for the end editing notification, but it never got called when Done was clicked; from a Google search it seems that only gets fired when the field resigns as the first responder - which is the bit I can't get to happen.

I then found answers on here that suggested adding self as the delegate and handling textFieldShouldReturn:. The problem is, as soon as I add self as the delegate, the keyboard no longer pops up when you click the field (and it doesn't gain focus) - it seems it isn't becoming first responder.

I tried handling textFieldShouldBeginEditing: and returning YES (docs say that should be the default if not overridden), and that got called, but made no difference. In my ignorance I tried [textField becomeFirstResponder] and was rewarded with a stack overflow (now I know that is called in response to trying to become first responder).

I'm now thoroughly stuck!

Can anyone help? I just want the keyboard to go away when the user clicks Done or presses [Return].

iLearner
  • 1,670
  • 2
  • 19
  • 45
  • remove anything else and add this delegate - (BOOL)textFieldShouldReturn:(UITextField *)theTextField { [theTextField resignFirstResponder];return YES; } – Paresh Navadiya Jun 14 '12 at 09:29
  • I assume you're saying 'use a separate object as the delegate' here? I've just discovered we shouldn't use a text field as its own delegate. I was getting an infinite loop when it was trying to show the keyboard - hence, no keyboard appearing. – Damaged Coconut Jun 14 '12 at 10:17

2 Answers2

2

Are you using an xib or doing it programatically? If you are using an xib then you may have forgotten to connect the delegate in File's Owner.

(BOOL)textFieldShouldReturn:(UITextField *)textField   
{
    [textField resignFirstResponder];
    return YES;
}

Try This one.

max_
  • 24,076
  • 39
  • 122
  • 211
iLearner
  • 1,670
  • 2
  • 19
  • 45
0

My fault. Turns out you're not supposed to set a text field's delegate to itself - there are complications due to unhandled selectors being forwarded to its delegate. If it doesn't respond to a selector the message goes to its delegate... which is itself, which we already know doesn't respond. Hence, an infinite loop.

Using a separate object as the delegate worked perfectly.

Hopefully this will help someone else avoid the same problem.