这可能有点长,但请耐心等待。它主要是简单的代码和日志输出。通常,如果我想将UITextField作为UITableViewCell的一部分,我可能会使用a)静态行或b)我将在情节提要中创建单元格,导出单元格并将字段导出到ViewController,然后将单元格拖到“表视图”外,但将其保留在场景中。
然而,我需要创建一个视图,在其中我接受来自28个不同事物的输入。我不想输出28个不同的UITextField。
我想动态地做这件事,让它更容易。因此,我创建了一个带有标签和UITextField的自定义UITableViewCell。
我的ViewController有两个数组。
@property (nonatomic, strong) NSArray *items;
@property (nonatomic, strong) NSArray *itemValues;
我的
cellForRowAtIndexPath
看起来像这样。。。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = @"ItemCell";
MyItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (!cell) {
cell = [[MyItemTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
cell.categoryValue.tag = indexPath.row;
cell.categoryValue.delegate = self;
}
cell.item.text = [self.items objectAtIndex:indexPath.row];
cell.itemValue.text = [self.itemValues objectAtIndex:indexPath.row];
return cell;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSInteger tag = [textField tag];
NSLog(@"TFSR tag: %zd/%zd", tag, self.categories.count-1);
if (tag < (self.categories.count - 1)) {
NSIndexPath *nextIndex = [NSIndexPath indexPathForRow:tag+1 inSection:0];
NSLog(@"TFSR nextRow: %zd/%zd\n", nextIndex.row);
FFFCategoryTableViewCell *cell = (MyItemTableViewCell *)[self.tableView cellForRowAtIndexPath:nextIndex];
[self.tableView scrollToRowAtIndexPath:nextIndex atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
[cell.categoryValue becomeFirstResponder];
}
else {
NSLog(@"DONE!");
}
return YES;
}
事实证明这是有问题的。目标是,用户应该能够选择第一行的UITextField,输入一个值,当他们按下键盘上的“下一步”键时,他们将被发送到第二行的UITextField。然后是第三、第四,。。。27日、28日。
但是,假设我首先在IndexPath.row=11的单元格上突出显示UITextField。如果我点击“下一步”,这是我的输出的样子。。。
======== OUTPUT ========
TFSR tag: 11/27
TFSR nextRow: 12/27
TFSR tag: 12/27
TFSR nextRow: 13/27
TFSR tag: 13/27
TFSR nextRow: 14/27
TFSR tag: 0/27
TFSR nextRow: 1/27
现在我完全明白为什么会发生这种情况。UITableView尝试在加载各种单元格时节省内存,并使用dequeueReusableCellWithIdentifier。。。我只有14个细胞(0-13)。然后循环回到开头。
我的问题是…我不知道解决这个问题的办法。我希望用户能够在第28行UITextField之前执行Next。
关于如何实现这一目标,有什么想法/解决方案?