iPhone: Jump to next uitextfield in uitableview, how to?

我怕爱的太早我们不能终老 提交于 2019-12-21 17:14:30

问题


In my iPhone project I'm using a UITableview with UITableViewCells containing UITextfields. I have seen in many apps that it is possible to use a next button to jump to the next textfield in the next cell. What is the best way to accomplish this?

My idea is to get the indexPath of the cell with the textfield that is being editing and then get the next cell by cellForRowAtIndexPath. But how can I get the indexPath of the cell I'm currently editing?

Thanks!


回答1:


  1. Keep references to the UITextField instances in your table view.
  2. Assign unique tag values to your UITextField instances.
  3. In your last text field, you might set its Return key type, which changes the keyboard's Return key label from "Next" to "Done": [finalTextField setReturnKeyType:UIReturnKeyDone];

In the UITextField delegate method -textFieldShouldReturn:, walk through the responders:

- (BOOL) textFieldShouldReturn:(UITextField *)tf {
    switch (tf.tag) {
        case firstTextFieldTag:
            [secondTextField becomeFirstResponder];
            break;
        case secondTextFieldTag:
            [thirdTextField becomeFirstResponder];
            break;
        // etc.
        default:
            [tf resignFirstResponder];
            break;
    }
    return YES;
}



回答2:


Assuming the UITextField was added to the UITableViewCell like below

UITableViewCell *cell;
UITextField *textField;
...
textField.tag = kTAG_TEXTFIELD;
[cell.contentView addSubview:textField];
...

You can get the current index path via

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
  if([textField.superView.superView isKindOfClass:[UITableViewCell class]]) {
    UITableViewCell *cell = (UITableViewCell *)textField.superView.superView;
    NSIndexPath *indexPath = [self.myTableView indexPathForCell:cell];
  }
  ...

The next row's UITextField would then be

NSIndexPath *indexPathNextRow = [NSIndexPath indexPathForRow:(indexPath.row+1) inSection:indexPath.section];
UITableViewCell *cellNextRow = (UITableViewCell *)[self.myTableView cellForRowAtIndexPath:indexPathNextRow];
UITextField *textFieldNextRow = (UITextField *)[cellNextRow.contentView viewWithTag:kTAG_TEXTFIELD];

Hope it helps!



来源:https://stackoverflow.com/questions/2825388/iphone-jump-to-next-uitextfield-in-uitableview-how-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!