【发布时间】:2015-10-15 15:51:00
【问题描述】:
我在 Objective-C 中有一个方法用于取消选中 UITableView 中的所有单元格:
- (void)resetCheckedCells {
for (NSUInteger section = 0, sectionCount = self.tableView.numberOfSections; section < sectionCount; ++section) {
for (NSUInteger row = 0, rowCount = [self.tableView numberOfRowsInSection:section]; row < rowCount; ++row) {
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section]];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.accessoryView = nil;
}
}
}
在 Swift 中,我认为我需要使用枚举来实现这一点。我对如何获得我需要的值感到困惑。这是我正在尝试做的“诗人物理学”草图:
func resetCheckedCells() {
// TODO: figure this out?
for (section, tableView) in tableView.enumerate() {
for (row, tableView) in tableView {
let cell = UITableView
cell.accessoryType = .None
}
}
}
这不起作用,但它说明了我想要完成的事情。我错过了什么?
更新
有一个非常简单但不明显(对我来说)的方法来做到这一点,涉及cellForRowAtIndexPath 和一个全局数组...
var myStuffToSave = [NSManagedObject]()
... 使用 UITableViewController 加载实例化。我发布此更新是希望其他人会发现它有帮助。
我的UITableViewController 最初填充的是NSManagedObjects。我的didSelectRowAtIndexPath 做了两件事:
1) 从全局 myStuffToSave 数组中添加/删除 NSManagedObjects
2) 在.Checkmark 和.None 之间为单元格切换cell.accessoryType
当调用cellForRowAtIndexPath 时,我会将myStuffToSave 中的项目与tableView 中的项目进行比较。
这是我的cellForRowAtIndexPath的sn-p:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
// I set the cells' accessory types to .None when they're drawn
// ** SO RELOADING THE tableView NUKES THE CHECKMARKS WITH THE FOLLOWING LINE... **
cell.accessoryType = .None
// boilerplate cell configuration
// Set checkmarks
// ** ...IF THE ARRAY IS EMPTY
if self.myStuffToSave.count > 0 {
// enumerate myStuffToSave...
for (indexOfMyStuffToSave, thingToSave) in stuffToSave.enumerate() {
// if the object in the array of stuff to save matches the object in the index of the tableview
if stuffInMyTableView[indexPath.row].hashValue == stuffToSave[indexOfMyStuffToSave].hashValue {
// then set its accessoryView to checkmark
cell.accessoryType = .Checkmark
}
}
}
return cell
}
因此,从myStuffToSave 中删除所有内容并重新加载 tableView 将重置所有选中的单元格。这就是我的resetCheckedCells 方法最后的样子:
func resetCheckedCells() {
// remove everything from myStuffToSave
self.myStuffToSave.removeAll()
// and reload tableView where the accessoryType is set to .None by default
self.tableView.reloadData()
}
感谢@TannerNelson 为我指出解决方案。
【问题讨论】:
-
仅供参考 - 这是移除所有电池配件的糟糕方法。只需在更新数据模型后重新加载表格视图,以便
cellForRowAtIndexPath方法正确绘制每个单元格。或者至少只迭代可见索引路径的列表。 -
顺便说一句 - 你的 Swift 代码可以像你的 Objective-C 代码一样工作。
-
谢谢。您在为我指明正确方向方面非常有帮助。非常感谢您的有益批评。
标签: ios swift uitableview swift2