【问题标题】:Problem: Multiple selection tableview cells being reused问题:多选表格视图单元被重用
【发布时间】:2011-06-14 07:06:31
【问题描述】:

我有一个表格视图,每次选择一行时都需要显示一个复选标记。 (多选)我的代码如下。我也可以取消选择一行。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath
{
static NSString *RootViewControllerCell = @"RootViewControllerCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RootViewControllerCell];

if(nil == cell)
{
    cell = [[[UITableViewCell alloc]initWithFrame:CGRectZero reuseIdentifier:RootViewControllerCell] autorelease];

}
cell.textLabel.font = [UIFont fontWithName:[NSString stringWithFormat:@"HelveticaNeue-Bold"] size:12];
textView.textColor = [UIColor colorWithRed:0.281 green:0.731 blue:0.8789 alpha:1];
cell.textLabel.text = [optionsArray objectAtIndex:[indexPath row]];
if (pathIndex == indexPath)
{
    if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
pathIndex = indexPath;
[surveytableView reloadData];
}

但我对重复使用的单元格有疑问。当我选择一个单元格时,其他地方的另一个单元格也会被选中。只有复选标记(或没有复选标记)被重用,其他细节(如行标题等)不会被重用。解决此问题的任何解决方案。提前致谢。

【问题讨论】:

标签: iphone objective-c uitableview


【解决方案1】:

添加到cellForRowAtIndexPath:

 if ([tableView.indexPathsForSelectedRows containsObject:indexPath]) {
     cell.accessoryType = UITableViewCellAccessoryCheckmark;
 } else if (![tableView.indexPathsForSelectedRows containsObject:indexPath]) {
     cell.accessoryType = UITableViewCellAccessoryNone;
 }

为我工作

【讨论】:

    【解决方案2】:

    在你的

    if (pathIndex == indexPath)
    

    你在比较指针而不是它们的值,试试

    [pathIndex isEqual:indexPath]
    

    或使用

    - (NSComparisonResult)compare:(NSIndexPath *)otherObject;
    

    接下来,您要为 pathIndex 分配一个值,而不是像这样保留或复制它

    pathIndex = [indexPath copy];
    

    (当然现在因为您要保留该值,所以在复制新对象之前,您必须释放前一个 [pathIndex release];)

    最后,您的实现没有提供多选,只有单选。您可以尝试向 NSMutableArray 添加和删除 NSIndexPath 对象,并检查它们是否存在于 cellForRowAtIndexPath 的可变数组中。

    【讨论】:

      【解决方案3】:

      问题是,如果当前行与 pathIndex 匹配,您只能对附件执行某些操作...。那么,如果它是一个普通单元格...?你永远不会把它放回去。你想要...

      cell.accessoryType = UITableViewCellAccessoryNone;
      
      if ([pathIndex isEqual:indexPath])
      {
         cell.accessoryType = UITableViewCellAccessoryCheckmark;
      }
      

      最好在设置任何特定属性之前重置单元格。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-16
        • 2023-04-01
        • 2010-12-23
        相关资源
        最近更新 更多