Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect UITextField Lost Focus

i searched a lot googling and heree, but nothing useful.

I have two textfields and i don't able to recognize which one lost the focus.
I tried all options, but nothing.

Here the textFieldDidEndEditing:

- (void) textFieldDidEndEditing:(UITextField *)textField {  
  NSLog(@"%@", [textField state]);
  NSLog(@"%d", [textField isSelected]);
  NSLog(@"%d", [textField isFirstResponder]);
  NSLog(@"%d", [textField isHighlighted]);
  NSLog(@"%d", [textField isTouchInside]);

  if ( ![textField isFirstResponder] || ![textField isSelected] ) {
  //if ( [textField state] != UIControlStateSelected) {
    NSLog(@"not selected!");
    [...]
    // remove view / etc...
  }
}

All NSLog returns 0! Why?!?

How can i detect lost focus? This method has called every time that i press a keyboard button, non only at the end!
Is there any alternatives?

EDIT:
I don't want to switch from texts but i want to detect lost focus when i click anyways on screen. (the keyboard will dismiss or not and the caret is not present on textfield)!

thanks.

like image 239
elp Avatar asked Jun 16 '11 09:06

elp


2 Answers

To handle tapping outside text fields you can override touchesBegan in your view controller:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event
{
    UITouch *touch = [[event allTouches] anyObject];
    if ([textField1 isFirstResponder] && (textField1 != touch.view))
    {
        // textField1 lost focus
    }

    if ([textField2 isFirstResponder] && (textField2 != touch.view))
    {
        // textField2 lost focus
    }

    ...
}
like image 167
Alexander Boiko Avatar answered Nov 03 '22 02:11

Alexander Boiko


 - (BOOL)textFieldShouldReturn:(UITextField *)textField {
      NSLog(@"%d",textFiled.tag);
      NSInteger nextTag = textField.tag + 1;
      UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];   
      if (nextResponder) {
          [nextResponder becomeFirstResponder];
      } else {          
          [textField resignFirstResponder];
      }
      return YES;
  }

The UITextField with tag had lost focus in textFieldShouldReturn method

This will help you to go from one TextField to another....just set tag incremently in all TextFields ex : 0,1,2,3....etc

like image 2
Mehul Mistri Avatar answered Nov 03 '22 03:11

Mehul Mistri