我的 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 中为某行进行选择时,它也会为我的其他部分选择相同的行索引。
我该如何解决这个问题?
最佳答案
我建议为您的 View Controller 维护一个数据模型,该模型为您的各个部分中的每个单元格保留所有选定状态。 (选择一个更恰当的名称来描述您的单元格项)。
struct Element {
var isSelected: Bool // selection state
}
然后你的 View Controller 将有一个数据模型:
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
将重用可能反射(reflect)您所选状态的单元格。
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)
}
}
希望这是有道理的!
关于ios - 如何跟踪使用 NSIndexPath 选择的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38666400/