gpt4 book ai didi

swift - 删除行后无法禁用对表的编辑

转载 作者:行者123 更新时间:2023-11-28 05:49:12 30 4
gpt4 key购买 nike

在我的 TableView 中,删除一条记录后,如果最后一条记录被删除,我希望它禁用编辑,但即使在调用 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 仍然是正确的。我在这里做错了什么?

最佳答案

我已经检查了你的代码,根据 Hikaru Watanabe 的评论,它不工作。所以我改变了 commit editingstyle 方法并且它工作正常,请检查下面的代码

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()
}

在 John 发表评论后更新 -

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()
}
}

关于swift - 删除行后无法禁用对表的编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53509866/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com