Here is the bar button behavior found in the system language settings:
- When the Edit bar button is pressed, the Back bar button will be replaced by the Cancel bar button.
- When the Done bar button is pressed, the Cancel bar button will be replaced by the Back bar button.
I am using UIViewController
.
I have no issue toggling between the Edit bar button and the Done bar button.
However, I am unsure how to toggle between the Back bar button and the Cancel bar button.
Could you guide me on how to achieve this?
This is my code snippet.
class NewViewController: UIViewController {
@IBOutlet weak var editBarButtonItem: UIBarButtonItem!
private var editMode: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func editButtonClick(_ sender: Any) {
if editMode {
editBarButtonItem.title = "Edit"
// TOD: How to provide a back bar button item at top left?
} else {
editBarButtonItem.title = "Done"
// TOD: How to provide a "Cancel" bar button item at top left?
}
editMode.toggle()
}
}
2
Answers
You can programmatically create UIBarButtonItem then set action for it.
Output here:
To start, do not create your own Edit/Done button.
UIViewController
has built-in support for this.editButtonItem
is provided for you. It toggles between "Edit" and "Done". When tapped, it calls theUIViewController
methodsetEditing:animated:
and it toggles theisEditing
property. All you need to do is override that method to app/remove the "Cancel" button.