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

but*_*aby 0 uitableview ios swift

我有多个部分UITableView,每个部分都有不同数量的UITableViewCells.

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

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

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
     someArray.append(indexPath)
}
Run Code Online (Sandbox Code Playgroud)

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

 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)
     }
 }
Run Code Online (Sandbox Code Playgroud)

我还想使每个部分一次只能选择一个单元格,并且每个部分的每个选择都保持不变。

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

我该如何解决?

Und*_*rea 5

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

struct Element {
    var isSelected: Bool // selection state
}
Run Code Online (Sandbox Code Playgroud)

然后你的视图控制器会有一个数据模型,如下所示:

 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)
Run Code Online (Sandbox Code Playgroud)

这个数组可能会被初始化为一堆元素,其中 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
  }
Run Code Online (Sandbox Code Playgroud)

(更有效的方法可能是保留每个部分的最后选择的行并将该行标记为 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)
    }
  }
Run Code Online (Sandbox Code Playgroud)

希望这是有道理的!