简体   繁体   中英

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

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. 在此处输入图片说明

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM