I have a bar button in the right side of the screen, it's barButtonSystemItem: .edit and it's used to put tableView in the editing mode. I want when, user tap on it, it change to barButtonSystemItem: .done and it close tableview from editing mode.
Just to be clear, every time that barButton is clicked, the type of it should be change from edit to done.
Here is my code, but it always stay with edit, and not changing to done
fileprivate func addBarButton() {
if tableView.isEditing {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(editButtonAction))
} else {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(doneButtonAction))
}
}
@objc func editButtonAction(sender: UIBarButtonItem) {
tableView.isEditing = !tableView.isEditing
}
@objc func doneButtonAction(sender: UIBarButtonItem) {
tableView.isEditing = !tableView.isEditing
}
override func viewDidLoad() {
super.viewDidLoad()
addBarButton()
tableView?.isEditing = true
}
In the bodies of methods
editButtonActionandeditButtonActionyou only change thetableViewediting state by doingtableView.isEditing = !tableView.isEditing. This action does nothing tonavigationItemat all.I'd recommend you to refactor the code a bit by renaming
addBarButtonintoupdateBarButtonand call it every time when thetableediting state changes and additionally fromviewDidLoadas you do now. So your code would become something like this: