不知道出了什么问题,我感觉这些年来我已经这样做了一千次,但这次不起作用。
我有一个 UIViewController (不是 UITableViewController),我在 loadView() 中创建了一个 UITableView。我设置了委托和数据源。我实现了
canMoveRowAt
和 moveRowAt
委托方法。我添加了一个 UIBarButtonItem 来点击以将表格置于编辑模式,但没有显示任何重新排序控件。
class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableview: UITableView!
override func loadView() {
// intentionally not calling super
self.tableview = UITableView(frame: .zero, style: .grouped)
self.tableview.delegate = self
self.tableview.dataSource = self
self.view = self.tableview
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableview.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
let reorderbutton = UIBarButtonItem(image: UIImage(systemName: "mount"), style: .plain, target: self, action: #selector(tappedreorder(_:)))
self.navigationItem.rightBarButtonItems = [reorderbutton]
}
@objc func tappedreorder(_ sender:Any) {
self.tableview.setEditing(true, animated: true)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var config = cell.defaultContentConfiguration()
config.text = ...
cell.contentConfiguration = config
return cell
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
print("moved row from \(sourceIndexPath) to \(destinationIndexPath)")
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
print("can move row at \(indexPath), true")
return true
}
}
当我将表格设置为编辑模式时,我没有收到任何对
canMoveRowAt
的回调,并且没有任何行显示重新排序控件。
我还尝试将
cell.showsReorderControl = self.tableview.isEditing
添加到 cellForRowAt
实现中,以便它显式请求移动控制,但这并没有改变任何内容,因为实际上没有任何行被重新加载。即使我将表格设置为编辑模式,然后执行 reloadData()
重新加载所有行并设置 cell.showsReorderControl
,它们仍然没有显示。
我想通了,我把自己搞砸了,因为我不想在进入编辑模式时出现删除控件,而且我搞乱了使用哪种方法来做到这一点。
我做的错误的事情是:
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return false
}
我的列表显示内置报告和自定义用户报告的列表。我不希望用户能够删除内置报告,因此我错误地使用
canEditRowAt
来关闭删除控件。但我应该做的是:
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
使用
editingStyleForRowAt
可以让我关闭“删除”控件,但仍允许“重新排序”控件。但是使用 canEditRowAt
关闭了所有编辑控件,包括我试图获取的重新排序控件。