Search code examples
iosios6uitextfielduitextfielddelegate

UITextField calls textFieldDidEndEditing when cleared but `text` property has data


Did anyone notice that UITextField calls textFieldDidEndEditing after clear button is pressed but text property still has old data ?

I'm not sure what code-sample I can provide here. I'm using storyboard if that matters.

For now I have to rely on taking data from all edit controls on main form's "Submit" button. But ideally I'd prefer to collect data in textFieldDidEndEditing handler.

Are there any better workarounds ?

I'm on iOS 6.

Update: Basically here is what I have on the form

  • UITextField and UiButton are on the form.
  • Keyboard dimissed by calling resignFirstResponder in handler of UITapGestureRecognizer

Steps to reproduce the issue:

  • Click on edit control. Enter some text.
  • Tap outside of text control.
  • textFieldDidEndEditing is called. Property .text has value I entered. All good.
  • Click on edit control again.
  • Click on clear button.
  • textFieldDidEndEditing is called again. But property .text still has value I just deleted !
  • Now as you see cursor blinking inside UITextField tap on Button on the form.
  • Keyboard is dismissed by textFieldDidEndEditing was never called.

I'll upload sample project on GitHub tomorrow.


Solution

  • I ran into the exact same problem. In my case, at least, it was due to having added a UITapGestureRecognizer to self.view (to allow for dismissing the keyboard if tapping outside of a UITextField) and setting cancelsTouchesInView=NO on the gesture recognizer. I had set that property in order to get hyperlinking working on a TTTAttributesLabel I have elsewhere in the View.

    My workaround was to watch for keyboard show and hide notifications, and toggle that property accordingly:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShowNotification:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHideNotification:) name:UIKeyboardDidHideNotification object:nil];
    

    (sign up for notifications)

    - (void)keyboardDidShowNotification:(NSNotification*)notification
    {
        tapGestureRecognizer.cancelsTouchesInView = YES;
    }
    
    - (void)keyboardDidHideNotification:(NSNotification *)notification
    {
        tapGestureRecognizer.cancelsTouchesInView = NO;
    }
    

    (handle notifications)

    The only problem, behavior-wise, is that the hyperlink still doesn't work when the keyboard is displayed: touching it will simply dismiss the keyboard, not forward the touch to the link handler. But I can live with that. After the keyboard is dismissed, the link works fine.