gpt4 book ai didi

ios - 如何使用文本字段处理 TableView 单元格

转载 作者:行者123 更新时间:2023-11-29 01:40:06 26 4
gpt4 key购买 nike

我的表格 View 单元格包含一个标签和一个文本字段,我正在重复使用我的单元格并且它正在工作。但是当我在第一个文本字段中输入文本并按回车键时,我想转到下一个文本字段,我该如何处理?

enter image description here

最佳答案

这就是我所做的:

  1. 使用以下方法创建了委托(delegate)协议(protocol):

    - (void)textFieldInCellDidReturn:(UITableViewCell*)cell;
    - (void)textFieldInCellDidBeginEditing:(UITableViewCell*)cell;
    - (void)textFieldInCellDidEndEditing:(UITableViewCell*)cell;
  2. 在单元格中:

    -(BOOL)becomeFirstResponder
    {
    return [self.inputTextField becomeFirstResponder];
    }

    -(void)textFieldDidBeginEditing:(UITextField *)textField
    {
    if ([self.delegate respondsToSelector:@selector(textFieldInCellDidBeginEditing:)])
    {
    [self.delegate textFieldInCellDidBeginEditing:self];
    }
    }
    -(void)textFieldDidEndEditing:(UITextField *)textField
    {
    if ([self.delegate respondsToSelector:@selector(textFieldInCellDidEndEditing:)])
    {
    [self.delegate textFieldInCellDidEndEditing:self];
    }
    }
    -(BOOL)textFieldShouldReturn:(UITextField *)textField
    {
    if ([self.delegate respondsToSelector:@selector(textFieldInCellDidReturn:)])
    {
    [self.delegate textFieldInCellDidReturn:self];
    }
    return NO;
    }
  3. 在 View Controller 和 TableView 委托(delegate)中,声明 iVar NSIndexPath* indexPathOfFirstResponder 并采用委托(delegate)

    - (void)textFieldInCellDidBeginEditing:(UITableViewCell *)cell
    {
    indexPathOfFirstResponder = [self.theTable indexPathForCell:cell];
    }

    -(void)textFieldInCellDidReturn:(UITableViewCell *)cell
    {
    NSIndexPath* indexPathForCell = [self.theTable indexPathForCell:cell];
    if(indexPathForCell.row < [self.theTable numberOfRowsInSection:indexPathForCell.section]-1)
    {
    NSIndexPath* nextIndexPathInSection = [NSIndexPath indexPathForRow:indexPathForCell.row+1 inSection:indexPathForCell.section];
    UITableViewCell* nextCellInSection = [self.theTable cellForRowAtIndexPath:nextIndexPathInSection];
    if (nextCellInSection)
    {
    [nextCellInSection becomeFirstResponder];
    }
    else
    {
    indexPathOfFirstResponder = nextIndexPathInSection;
    [self.theTable scrollToRowAtIndexPath:nextIndexPathInSection atScrollPosition:(UITableViewScrollPositionMiddle) animated:YES];
    }
    }
    else
    {
    [self.theTable endEditing:YES];
    }
    }

    -(void)textFieldInCellDidEndEditing:(UITableViewCell *)cell
    {
    indexPathOfFirstResponder = nil;
    }

    -(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
    {
    if ([indexPath isEqual:indexPathOfFirstResponder])
    {
    [cell becomeFirstResponder];
    }
    }

关于ios - 如何使用文本字段处理 TableView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32493998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com