How is the editButtonItem object instantiated?

41 Views Asked by At

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
    }
}
2

There are 2 best solutions below

0
Jaya Mayu On BEST ANSWER

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.

0
rmaddy On

I think you are asking about this line:

navigationItem.leftBarButtonItem = editButtonItem

editButtonItem is from UIViewController. Note that this is a read-only property. The implementation is probably a lazy computed property that creates the button the first time you access the property. It's part of the UIViewController implementation.