Search code examples
swiftuibarbuttonsystemitem

How is the editButtonItem object instantiated?


I'm following a tutorial on using the Keychain and I prefer to understand how the code works before diving into the tutorial. I noticed that in this class called MasterViewController, it assigns a UIBarButtonItem with a style of edit to the navigationItem.leftBarButtonItem variable. The code doesn't instantiate this edit button anywhere in the codebase so I'm curious to know how does this work? When I try to do the following, it doesn't work:

navigationItem.rightBarButtonItem = camera

Why is this?

The tutorial I'm following is found here on the Ray Weinerlich Website :

Here is the code for the MasterViewController:

    class MasterViewController: UIViewController, UITableViewDelegate {

  // MARK: - IBOutlets
  @IBOutlet var tableView: UITableView!

  // MARK: - Properties
  var detailViewController: DetailViewController?
  var managedObjectContext: NSManagedObjectContext?
  var isAuthenticated = false
  var didReturnFromBackground = false
  var _fetchedResultsController: NSFetchedResultsController<Note>?

  // MARK: - View Life Cycle
  override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.leftBarButtonItem = editButtonItem


    let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:)))
    navigationItem.rightBarButtonItem = addButton

    if let split = splitViewController {
      let controllers = split.viewControllers
      detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
    }
}

Solution

  • It's a built-in UIBarButton item available readily for users to use. You can directly use it and it'll toggle between edit and done.

    See the documentation below. enter image description here

    If you have a doubt with an object or variable, just Command + click on that variable and object and you could check more about it.