如何跟踪使用NSIndexPath选择的单元格?

时间:2016-07-29 19:43:20

标签: ios swift uitableview

我的UITableView中有多个部分,每个部分都有UITableViewCells个不同的部分。

我想跟踪为每个部分选择的单元格,并显示已选择的单元格的图像。

所以我在考虑将它们存储在一个数组中:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
     someArray.append(indexPath)
}

然后显示已选择的单元格的图像:

 for indices in self.someArray {
     if indices == indexPath {
         cell.button.setImage(UIImage(named: "selected"), forState: UIControlState.Normal)
     } else {
         cell.button.setImage(UIImage(named: "unselected"), forState: UIControlState.Normal)
     }
 }

我也希望这样做,以便每次只能选择每个部分一个单元格,并且每个部分的每个选择都会保留。

这些选择不会保持原样。每次我在第0部分中为某行进行选择时,它也会为其他部分选择相同的行索引。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

我建议为视图控制器维护一个数据模型,该模型保留各个部分中每个单元格的所有选定状态。 (选择一个更恰当的名称来描述您的单元格项目。)

struct Element {
    var isSelected: Bool // selection state
}

然后您的视图控制器将具有如下数据模型:

 var dataModel: [[Element]] // First array level is per section, and second array level is all the elements in a section (e.g. dataModel[0][4] is the fifth element in the first section)

这个数组很可能被初始化为一堆元素,其中isSelected为false,假设你从取消选择的所有行开始。

现在你的tableView:didSelectRowAtIndexPath函数看起来像这样:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    // Check if there are any other cells selected... if so, mark them as deselected in favour of this newly-selected cell
    dataModel[indexPath.section] = dataModel[indexPath.section].map({$0.isSelected = false}) // Go through each element and make sure that isSelected is false

    // Now set the currently selected row for this section to be selected
    dataModel[indexPath.section][indexPath.row].isSelected = true
  }

(更有效的方法可能是保留每个部分的最后一个选定行并标记为false而不是映射整个子数组。)

现在,在tableView:cellForRowAtIndexPath中,您必须显示是否根据您的dataModel选择了一个单元格。如果您未在数据模型中维护所选状态,则一旦单元格滚出屏幕,它将失去其选定状态。此外,如果您没有正确刷新单元格,dequeueReusableCellWithIdentifier将重复使用可能反映您所选状态的单元格。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("yourCellIdentifier") as! YourCellType

    // If your data model says this cell should be selected, show the selected image
    if dataModel[indexPath.section][indexPath.row].isSelected {
      cell.button.setImage(UIImage(named: "selected"), forState: UIControlState.Normal)
    } else {
      cell.button.setImage(UIImage(named: "unselected"), forState: UIControlState.Normal)
    }
  }

希望有意义!