2016-09-19 55 views
-1

我有一个表格视图,我想改变选定的表格视图选中的单元格颜色,并且滚动表格视图时单元格颜色没有改变。有我的代码:Store TableView selected Row

override func tableView(tableView: UITableView, didSelectRowAtIndexPath 
indexPath: NSIndexPath) { 
    let selectCell = tableView.indexPathForSelectedRow 
     self.selectedCell.append(selectCell!) 
for i in selectedCell 
     { 
      if(!(i .isEqual(indexPath))) 
      { 
       let currentCell = tableView.cellForRowAtIndexPath(i)! as UITableViewCell 

       currentCell.backgroundColor = UIColor.lightGrayColor() 
      } 
     } 

这是滚动表视图时代码崩溃。

+0

制作一个变量,该变量将在选择时将当前的indexpath.row存储在didSelectRowAtIndexPath上。现在检查cellForRowAtIndexPath里面的当前indexpath.row。如果存储的indexpath.row匹配,则更改颜色。 – Tuhin

+0

你需要改变所有选定的索引颜色? –

+0

如果您需要更改所有选定的行颜色,请将所选索引保存在didSelectRowAtIndexPath方法的数组中,并在cellForRowAtIndexPath方法中检查索引路径是否存在于数组中,然后进行处理 –

回答

2

你的代码对我来说似乎很陌生。每次选择一个单元格时,不需要设置所有其他单元格的背景颜色。定义你的celectedCellsInt:Bool类型的字典,以便您可以将其设置为true每个indexpath.row这样的:

var selectedCells = [Int: Bool]() 

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    if let cell = tableView.cellForRowAtIndexPath(indexPath) { 
     cell.backgroundColor = UIColor.lightGrayColor() 
     selectedCells[indexPath.row] = true 
    } 
} 

,然后在cellForRowAtIndexPath方法检查字典设置的backgroundColor,就像这样:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("YourCellIdentifier", forIndexPath: indexPath) 

    if selectedCells[indexPath.row] == true { 
     // Color for selected cells 
     cell.backgroundColor = UIColor.lightGrayColor() 
    } else { 
     // Color for not selected cells 
     cell.backgroundColor = UIColor.whiteColor() 
    } 
    //Rest of your Cell setup 

    return cell 
}