在单个UITableCell触摸上应用多个UITableViewCellAccessoryCheckmark的问题

时间:2011-12-30 15:29:09

标签: objective-c uitableview

所以我的UITableView中有很多单元格并且在触摸单元格时,其他单元格在视图之外也会应用刻度线。我相信这是因为正在重复使用单元格或由dequeueReusableCellWithIdentifier:

引起的

继承我的代码:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

            if (cell.accessoryType == UITableViewCellAccessoryNone){
                [addPapersSelectedRowsArray addObject:[NSNumber numberWithInt:indexPath.row]];
                [cell setAccessoryType:UITableViewCellAccessoryCheckmark];

            }
            else if (cell.accessoryType == UITableViewCellAccessoryCheckmark){
                cell.accessoryType = UITableViewCellAccessoryNone;
                [addPapersSelectedRowsArray removeObject:[NSNumber numberWithInt:indexPath.row]];
            }


    }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }



    NSDictionary *currentPapersSecltion = [papersDataDictionary objectAtIndex:indexPath.row];
    [[cell textLabel] setText:[currentPapersSecltion objectForKey:@"Title"]]; 



   return cell;

}

还从viewDidLoad中的.plist中提取数据:

 //Load papers data from the local plist
    papersDataDictionary = [[[NSDictionary alloc] initWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"papers.plist"]] objectForKey:@"Rows"];

有谁知道如何解决这个问题? 谢谢你们!

塞米松

2 个答案:

答案 0 :(得分:3)

在cellForRowAtIndexPath中,您需要根据是否已选择单元格来设置复选标记。

if ([addPapersSelectedRowsArray containsObject:[NSNumber numberWithInt:[indexPath row]]]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
return cell;

答案 1 :(得分:-1)

  UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

   // add this line
  cell.accessoryType = UITableViewCellAccessoryNone;

    if (cell.accessoryType == UITableViewCellAccessoryNone){
        [addPapersSelectedRowsArray addObject:[NSNumber numberWithInt:indexPath.row]];
        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];

    }
    else if (cell.accessoryType == UITableViewCellAccessoryCheckmark){
        cell.accessoryType = UITableViewCellAccessoryNone;
        [addPapersSelectedRowsArray removeObject:[NSNumber numberWithInt:indexPath.row]];
    }
  //add this line as well
   [tableView reloadData];