use*_*240 1 uitableview ios swift
有没有一种方法可以防止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)
}
Run Code Online (Sandbox Code Playgroud)
您将需要实现该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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
524 次 |
| 最近记录: |