Tableview滚动更改选择

时间:2014-12-14 16:20:11

标签: ios swift

我查看了几个与此相关的StackOverflow问题,但似乎还没有很好地理解这个概念。

我有一个带有几个单元格的tableview,我使用枚举填充。当我向下滚动行时,表中的另一行会被选中。我实现了以下方法:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCellWithIdentifier("activityCell", forIndexPath: indexPath) as UITableViewCell

    cell.textLabel?.text = activities[indexPath.item].rawValue;

    return cell;
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    var cell = tableView.cellForRowAtIndexPath(indexPath);
    cell?.selected = true;

}

我知道细胞是可重复使用的,但我无法正确理解这个概念以及它是如何应用的。

你能给我一些帮助吗?

干杯

2 个答案:

答案 0 :(得分:1)

如果您要重复使用单元格,请按照您已完成的方式将单元格设置为selected中的didSelectRowAtIndexPath,这将使重用的单元格也反映出已更改的{{1}属性。相反,我建议为您的活动对象添加一个布尔selected属性,以便可以在selected中进行选择更改,例如:

cellForRowAtIndexPath:

答案 1 :(得分:0)

  

正如拜伦建议的那样,我们可以通过保存选中来处理这种情况   数组中的索引路径,并在未选中时从数组中删除它们。

var indexArray  : [NSIndexPath]?
  

在将表加载为

之前初始化indexArray
self.indexArray = []
  

细胞选择&取消选择必须在委托函数的帮助下反映在indexArray中:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
                cell.accessoryType = .checkmark
                self.indexArray?.append(indexPath as NSIndexPath)
        }
       }

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

        if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
            cell.accessoryType = .none
            if let pos = self.indexArray?.index(of: indexPath as NSIndexPath)
            {
                self.indexArray?.remove(at: pos)
            }
        }
       }
  

现在,当为每一行调用 cellForRowAtIndexpath 函数时,检查当前indexPath是否存在于indexArray中。如果是,则已经选择了该单元,否则,该单元处于未选择状态&在单元格上执行相应的任务。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier") as! YourTableViewCell

    if (self.indexArray?.contains(indexPath as NSIndexPath))!
    {
        cell.accessoryType = .checkmark
    }
    else
    {
        cell.accessoryType  = .none
    }
    return cell
}
相关问题