有没有办法防止tableView中的单元格被移动到不同的部分?
sections
具有不同类型单元格的数据,因此当用户尝试将单元格拖动到不同的部分时,应用程序崩溃。
我想只允许用户移动部分内的单元格,而不是在部分之间。
相关代码如下:
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let reorderedRow = self.sections[sourceIndexPath.section].rows.remove(at: sourceIndexPath.row)
self.sections[destinationIndexPath.section].rows.insert(reorderedRow, at: destinationIndexPath.row)
self.sortedSections.insert(sourceIndexPath.section)
self.sortedSections.insert(destinationIndexPath.section)
}
你需要实现UITableViewDelegate
方法targetIndexPathForMoveFromRowAt
。
如果源和目标section
相同,您的策略是允许移动。如果不是那么你可以返回第0行,如果建议的目标部分小于源部分,或者如果建议的目标部分大于源部分,则返回部分的最后一行。
这将限制移动到源部分。
override func tableview(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
let sourceSection = sourceIndexPath.section
let destSection = proposedDestinationIndexPath.section
if destSection < sourceSection {
return IndexPath(row: 0, section: sourceSection)
} else if destSection > sourceSection {
return IndexPath(row: self.tableView(tableView, numberOfRowsInSection:sourceSection)-1, section: sourceSection)
}
return proposedDestinationIndexPath
}
查看此Apple doc链接
你需要管理条件
targetIndexPathForMoveFromRowAtIndexPath
可以MoveRowAtIndexPath