在我的应用程序中,用户根据他/她选择的单元格更改 tableView 中显示的字段。(仅供参考...我允许选择多个单元格。)就在用户按下后退按钮时,程序将所选单元格的 textLabel 复制到父 viewController 的占位符。
这是我的代码的相关部分:
- (void)willMoveToParentViewController:(UIViewController *)parent
{
int tempCount = 0;
for (int section = 0; section < 3; section++)
{
int rowMax;
if (section == 0)
rowMax = 3;
else if (section == 1)
rowMax = 5;
else if(section == 2)
rowMax = 3;
for(int row = 0; row < rowMax; row++)
{
NSIndexPath *tempIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell *selectedCell = [self.tableView cellForRowAtIndexPath:tempIndexPath];
if(selectedCell.accessoryType == UITableViewCellAccessoryCheckmark)
{
NSLog(@"tempCount = %d", tempCount);
tempCount++;
if (tempCount == 1)
chosenFieldsViewController.field0.placeholder = selectedCell.textLabel.text;
else if(tempCount == 2)
chosenFieldsViewController.field1.placeholder = selectedCell.textLabel.text;
else if(tempCount == 3)
chosenFieldsViewController.field2.placeholder = selectedCell.textLabel.text;
}
}
}
}
我意识到,如果向下滚动 tableView,选择单元格后,所选单元格不会在 parentVC 上显示为 placeHolder。根据我的分析,我认为一旦向下滚动,单元格就会从内存中删除。因此,尽管选择了单元格,但它们无法显示在父 VC 上。
如果是这样,为什么我在向上滚动时看到单元格被选中?
如果有人能建议我如何在用户滚动时跟踪选定的单元格,我将不胜感激。
谢谢。
编辑 1
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
if(selectedCell.accessoryType != UITableViewCellAccessoryCheckmark && count<3)
{
selectedCell.accessoryType = UITableViewCellAccessoryCheckmark;
count ++;
}
else if(selectedCell.accessoryType == UITableViewCellAccessoryCheckmark)
{
selectedCell.accessoryType = UITableViewCellAccessoryNone;
count--;
}
}
编辑 2
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:@"CellForRow%dSection%d",indexPath.row, indexPath.section];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone; // VERY IMPORTANT
if (indexPath.section == 0)
{
switch(indexPath.row)
{
case 0:
cell.textLabel.text = @"Class A";
break;
case 1:
cell.textLabel.text = @"Class B";
break;
case 2:
cell.textLabel.text = @"Class C";
break;
default:
break;
}
}
if(indexPath.section == 1)
{
switch(indexPath.row)
{
case 0:
cell.textLabel.text = @"Class D";
break;
case 1:
cell.textLabel.text = @"Class E";
break;
case 2:
cell.textLabel.text = @"Class F";
break;
case 3:
cell.textLabel.text = @"Class G";
break;
case 4:
cell.textLabel.text = @"Class H";
break;
default:
break;
}
}
if(indexPath.section == 2)
{
switch (indexPath.row)
{
case 0:
cell.textLabel.text = @"Class I";
break;
case 1:
cell.textLabel.text = @"Class J";
break;
case 2:
cell.textLabel.text = @"Class K";
break;
default:
break;
}
}
return cell;
}