IPhone:选择不同的行



当我从UITableView中选择一行时,该行和下面的其他行(所选行下面的几行)也会被选中。只有选定的行才应是选定的行。

我的代码是:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
    //Deselect
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.backgroundColor=[UIColor clearColor];
} else {
    //Select
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    cell.backgroundColor=[UIColor redColor];
}
}

提前感谢!

这可能是因为单元格被重复使用。如果你想使用背景色来显示所选的状态,你需要在单元格geter方法中设置它

添加此代码应该有效:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //...
    if (!cell.selected) {
        //Deselected
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.backgroundColor=[UIColor clearColor];
    } else {
        //Selected
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        cell.backgroundColor=[UIColor redColor];
    }
}

是的,您必须声明数据源计数的新NSMutableArray(比如_selectedList)。用值为0的NSNumber填充它。

在.h文件中声明NSMutableArray *_selectedList;(作为类成员)

viewDidLoadinit方法中,

_selectedList = [[NSMutableArray alloc] init];
for( int i = 0; i < [datasource count]; i++ )
{
  [_selectedList addObject:[NSNumber numberWithBool:NO]];
}

并按如下方式制作以下方法。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //...
    if (! [[_selectedList objectAtIndex:indexPath.row] boolValue]) {
        //Deselected
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.backgroundColor=[UIColor clearColor];
    } else {
        //Selected
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        cell.backgroundColor=[UIColor redColor];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
    //Deselect
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.backgroundColor=[UIColor clearColor];
  } else {
    //Select
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    cell.backgroundColor=[UIColor redColor];
  }
  BOOL isSelected = ![[_selectedList objectAtIndex:indexPath.row] boolValue];
  [_selectedList replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:isSelected]];
}

最新更新