Sender: AnyObject crashes when UIBarButtonItem is pressed

132 views Asked by At

I am having trouble understanding how to create a BarButtonItem and set the sender to AnyObject. I created a BarButtonItem programmatically and tried to set the sender as any object but the app crashes when the button is pressed.

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    var toggle = UIBarButtonItem(title: "Settings", style: UIBarButtonItemStyle.Plain, target: self, action: "toggleSideMenu")
    self.navigationItem.leftBarButtonItem = toggle

  }

func toggleSideMenu(sender: AnyObject) {
    toggleSideMenuView()
}
1

There are 1 answers

1
Droppy On BEST ANSWER

That "selector" has a parameter, so it should be:

action: "toggleSideMenu:"
                       ^

Plus the method itself will need an @objc annotation and I'm pretty sure that sender is optional, so:

@objc func toggleSideMenu(sender: AnyObject?) {
    toggleSideMenuView()
}