Swift - tableView中的可移动行仅在一个部分内,而不是在一个部分之间

问题描述 投票:1回答:2

有没有办法防止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)
}
ios swift uitableview
2个回答
2
投票

你需要实现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
}

0
投票

查看此Apple doc链接

https://developer.apple.com/library/ios/documentation/userexperience/conceptual/tableview_iphone/ManageReorderRow/ManageReorderRow.html

你需要管理条件

targetIndexPathForMoveFromRowAtIndexPath

可以MoveRowAtIndexPath

© www.soinside.com 2019 - 2024. All rights reserved.