我建议为您的视图控制器维护一个数据模型,该视图控制器将保留您各个部分中每个单元的所有选定状态。 (选择一个更贴切的名称来描述您的单元格项目)。
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是假的,假设你开始取消所有行。现在
您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
}
(一种更有效的方式可能是让每个部分选择的最后一行,并标注虚假的,而不是映射整个子阵列)
现在,在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)
}
}
希望有道理!
有道理。所以它xcode不喜欢这行:dataModel [indexPath.section] = dataModel [indexPath.section] .map({$ 0.isSelected = false}) –
此外,我得到:致命错误:索引超出范围如果dataModel [indexPath.section] [indexPath.row] .isSelected { –
对不起,我没有尝试自己运行代码!你可以用一个for循环替换地图,通过子数组中的每个元素,并确保它被取消选择。至于索引超出范围,也许你需要实现tableView:numberOfSectionsInTableView来返回正确数量的节,类似于tableView:numberOfRowsInSection。两者都应该返回基于你的dataModel的.count属性的值,这样你不应该得到一个索引超出范围... – Undrea