简体   繁体   中英

UITextfield become first responder not working

I have a toolbar on top of the keyboard with a prev and next button. When I press the next button the next textfield should become first responder but this doesn't happen. Here is my code.

-(IBAction) nextfield {
    if([name isFirstResponder] == TRUE) {
        [name resignFirstResponder];
        [surname becomeFirstResponder];
        if(surname.editing == TRUE)
            NSLog(@"surname");
    }
    if([surname isFirstResponder] == TRUE) {
        [email becomeFirstResponder];
    }
    if([email isFirstResponder] == TRUE) {
        [password becomeFirstResponder];
    }
    if([password isFirstResponder] == TRUE) {
        [confirm becomeFirstResponder];
    }
    if([confirm isFirstResponder] == TRUE) {
        [country becomeFirstResponder];
    }
    if([country isFirstResponder] == TRUE) {
        if(country.text == @"United States") {
            [state setEnabled:TRUE];
            [state becomeFirstResponder];
        }
        else {
            [type becomeFirstResponder];
        }
    }
    if([state isFirstResponder] == TRUE) {
        [type becomeFirstResponder];
    }
    if ([type isFirstResponder] == TRUE) {
        [name becomeFirstResponder];
    }
}

I get in Log "surname" but the cursor doesn't show up and if i type something it doesn't appear anywhere.

So you're checking to see if name is the first responder, and if it is, then making surname the first responder.

Then you check and see if surname is the first responder, and if it is, you make email the first responder.

Then you check and see if email is the first responder, and if it is....

Your problem is that every one of those if statements is true, because becoming first responder is an immediate thing.

In other words, you should be using else if (...) statements instead of discrete if statements.

create an array of textfield object lets say textFieldArray. then on prev and next button tab call following func

 -(void)gotoPrevTextfield

{
  for(int i=1 ;i<[textFieldArray count];i++)
{
    if([textFieldsArray [i] isFirstResponder])
    {
        [textFieldsArray[i-1] becomeFirstResponder];
        [textFieldsArray [i] resignFirstResponder];

         break;
    }
}}

    -(void)gotoNextTextfield
   {
for( int i=0 ;i<[textFieldArray count];i++)
{
    if([textFieldsArray [i] isFirstResponder])
    {
        [textFieldsArray [i+1] becomeFirstResponder];
        [textFieldsArray [i] resignFirstResponder];

        break;
    }
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM