【发布时间】:2020-01-14 20:52:56
【问题描述】:
class TableViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var array = ["1","2","3"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
tableView.delegate = self
tableView.isScrollEnabled = false
tableView.dragInteractionEnabled = true
tableView.dragDelegate = self
tableView.dropDelegate = self
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return array.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.textLabel?.text = array[indexPath.section]
return cell
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let item = array[sourceIndexPath.section]
array[sourceIndexPath.section] = array[destinationIndexPath.section]
array[destinationIndexPath.section] = item
tableView.beginUpdates()
tableView.reloadData()
tableView.endUpdates()
}
}
extension TableViewController: UITableViewDragDelegate {
func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
return [UIDragItem(itemProvider: NSItemProvider())]
}
}
extension TableViewController: UITableViewDropDelegate {
func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
}
func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
if tableView.hasActiveDrag {
if session.items.count > 1 {
return UITableViewDropProposal(operation: .cancel)
} else {
return UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
}
} else {
return UITableViewDropProposal(operation: .copy, intent: .insertAtDestinationIndexPath)
}
}
}
当我尝试重新排序单元格时,此代码会因此错误而崩溃。当我在行中而不是部分执行时,它工作得非常好。
这是错误日志:
TableViewSample[45038:397348] *** 由于未捕获而终止应用程序 异常'NSInternalInconsistencyException',原因:'试图移动 索引路径 ( {长度 = 2, 路径 = 2 - 0}) 索引路径 ( {length = 2, path = 0 - 1}) 不存在 - 更新后第 0 部分只有 1 行'
【问题讨论】:
-
你重新订购什么?能详细点吗?
-
'重新排序'?还是重新排序?
-
很明显,您使用的 sourceIndexPath 和 destinationIndexPath 参数不正确。
标签: ios swift uitableview