Не удается отключить редактирование таблицы после удаления строки - PullRequest
0 голосов
/ 28 ноября 2018

В моем табличном представлении после удаления записи я хочу отключить редактирование, если последняя запись была удалена, но даже после вызова 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 все еще верно.Что я тут не так делаю?

Ответы [ 2 ]

0 голосов
/ 28 ноября 2018

Вы должны использовать этот метод:

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return editingEnable
}

Просто установите true или false для этой переменной "editEnable" в ваших условиях.

0 голосов
/ 28 ноября 2018

Я проверил ваш код, согласно комментарию Хикару Ватанабе, он не работает.Поэтому я внес изменения в метод commit editstyle , и он работает нормально, пожалуйста, проверьте код ниже

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()
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...