【发布时间】:2016-03-17 12:54:12
【问题描述】:
我希望一个单元格在被触摸时保持选中状态,如果再次被触摸则取消选中。这是我的代码不起作用:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell = tableView.cellForRowAtIndexPath(indexPath)
if let value = selectedCell?.selected.boolValue {
if !value {
print("cell was selected and will remain selected")
selectedCell?.selected = true
} else {
print("cell is deselected")
selectedCell?.selected = false
}
}
}
我该如何实现?
【问题讨论】:
-
您需要将单元格状态保存在一个数组中,然后在 cellForRowAtIndexPath 中使用它来区分应该选择哪个单元格,哪些不应该选择。
-
以及如何取消选择之后的选择。现在我只想让它适用于一个单元格。但是数组的想法将是必要的,因为我正在实施一个完整的菜单来使用此功能
-
你需要实现didSelectRowAtIndexPath和didDeselectRowAtIndexPath,
-
在此之前创建一个数组,该数组将具有与单元格相同数量的对象。在数组中为所有对象添加 @"NO" 字符串。然后是在didSelectRowAtIndexPath 中简单地做arrayCellState replaceObjectAtIndexPath: indexPath.row withObject:@"YES" 反之亦然在didDeselectRowAtIndexPath 中。然后在 cellForRowAtIndexPath 检查选定的单元格 if([[arrayCellState objectAtIndex:indexPath.row] isEqualToString: @"YES"]) ,如果是 cell.setSelected = YES;反之亦然。
标签: ios swift uitableview