我找到了解决方案。 UITableViewCell 拒绝绘制重新排序控件,除非它处于编辑模式。幸运的是,UITableViewCell 和 UITableView 轨道编辑是分开的,而且至关重要的是,UITableView 实际上处理重新排序,而不管它自己的编辑模式如何。我们只需要欺骗单元格来绘制重新排序控件,我们就可以回家了。
子类UITableViewCell 像这样:
class ReorderTableViewCell: UITableViewCell {
override var showsReorderControl: Bool {
get {
return true // short-circuit to on
}
set { }
}
override func setEditing(editing: Bool, animated: Bool) {
if editing == false {
return // ignore any attempts to turn it off
}
super.setEditing(editing, animated: animated)
}
}
现在只需在要启用重新排序的单元格上设置editing = true。你可以让它以-tableView:canMoveRowAtIndexPath:为条件。
在您的表格视图数据源中:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
// Configure the cell...
:
cell.editing = self.tableView(tableView, canMoveRowAtIndexPath: indexPath) // conditionally enable reordering
return cell
}
唯一的缺点是这与表格视图allowsMultipleSelectionDuringEditing选项不兼容;编辑控件总是错误地显示。一种解决方法是仅在实际的表格视图编辑期间启用多项选择。
在您的表格视图控制器中:
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
self.tableView.allowsMultipleSelectionDuringEditing = editing // enable only during actual editing to avoid cosmetic problem
}
另外,在-viewDidLoad 或您的故事板中,将allowsMultipleSelectionDuringEditing 的初始值设置为false。