在表视图中,删除记录后,如果删除了最后一条记录,我希望它禁止编辑,但是即使调用setEditing
后状态也不会改变。这是一个仍然显示行为的简化示例:
class TestViewController: UITableViewController {
var items = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItems = [
UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(add)),
UIBarButtonItem(title: "Remove", style: .plain, target: self, action: #selector(remove))
]
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
self.items.remove(at: indexPath.row)
if self.items.count == 0 {
// This is getting executed, but not changing the table's state
self.tableView.setEditing(false, animated: false)
}
self.tableView.reloadData()
}
@objc func add () {
self.items.append("foo")
self.tableView.reloadData()
}
@objc func remove () {
self.tableView.setEditing(!self.tableView.isEditing, animated: true)
}
}
单击“删除”按钮可以打开和关闭编辑,没有任何问题,但是如果删除最后一个然后添加一个新的,它仍会显示在编辑模式下。我尝试单步执行代码,它肯定达到了正确的行,但是即使执行了tableView.isEditing
仍然正确。我在这里做什么错了?
答案 0 :(得分:1)
我已经检查了您的代码,按照渡边光(Hikaru Watanabe)的评论,它不起作用。 因此,我对 commit editstylestyle 方法进行了更改,并且效果很好, 请检查以下代码
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
self.items.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .left)
if self.items.count == 0 {
// This is getting executed, but not changing the table's state
self.tableView.setEditing(false, animated: false)
}
//self.tableView.reloadData()
}
在约翰发表评论后更新-
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
self.items.remove(at: indexPath.row)
if self.items.count == 0 {
// This is getting executed, but not changing the table's state
self.tableView.deleteRows(at: [indexPath], with: .none)
self.tableView.setEditing(false, animated: false)
}else{
self.tableView.reloadData()
}
}
答案 1 :(得分:0)
您应该使用此方法:
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return editingEnable
}
只需根据您的条件将此变量“ editingEnable”设置为true或false。