Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate Tab Key Press in iOS SDK

When a hardware keyboard is used with iOS, pressing tab or shift-tab automatically navigates to the next or previous logical responder, respectively. Is there a way to do the same programmatically (i.e. simulating the tab key rather than keeping track of the logical order manually)?

like image 246
Brian Westphal Avatar asked Oct 15 '10 18:10

Brian Westphal


2 Answers

As William Niu is right but you can also use this code explained below.

I have used this and got success.Now consider the example of UITextField...

You can use UITextView's delegate method -(BOOL)textFieldShouldReturn:(UITextField*)textField as explained below.

But before doing this you should have to give tag to each UITextField in an Increment order...(Increment order is not required necessary ,but as for my code it is required, you can also use decrement order but some code changes for doing this)

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    NSInteger nextTag = textField.tag + 1;
    UIResponder* nextResponder = [self.view viewWithTag:nextTag];   
    if (nextResponder) {
        [nextResponder becomeFirstResponder];       
    } else {
        [textField resignFirstResponder];
    }
    return YES;
}

Hope this will work for you...

Happy coding....

like image 132
Mehul Mistri Avatar answered Oct 04 '22 06:10

Mehul Mistri


You may define the "tab-order" using the tag property. The following post describes how to find the next tag index to go to for UITextFields, How to navigate through textfields (Next / Done Buttons).

Here is a modified version of the code from that post. Instead of removing keyboard at the last tag index, this following code would try to loop back to the first tag index.

-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
  NSInteger nextTag = textField.tag + 1;
  // Try to find next responder
  UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
  if (nextResponder) {
    // Found next responder, so set it.
    [nextResponder becomeFirstResponder];

    return NO;
  }

  // Try to find the first responder instead...
  // Assuming the first tag index is 1
  UIResponder* firstResponder = [textField.superview viewWithTag:1];
  if (firstResponder) {
    // loop back to the first responder
    [firstResponder becomeFirstResponder];
  } else {
    // Not found, so remove keyboard.
    [textField resignFirstResponder];
  }

  return NO; // We do not want UITextField to insert line-breaks.
}

If you want an UI element other than UITextField, you should still be able to use the same logic, with a few more checks.

like image 29
William Niu Avatar answered Oct 04 '22 07:10

William Niu