Alex Donner Alex Donner - 27 days ago 12
Swift Question

Swift Error/Crash when setting NavigationButton

Does anybody know why my code Crashed/doesn't work?


Answer Source

You need to declare your UIBarbuttonItem in your viewDidLoad. Self won´t be recognised otherwise.

override func viewDidLoad() {
    let rightBarButton = UIBarButtonItem(title: "Edit", style: .done, target: self, action: #selector(buttonClicked(_:)))
    self.navigationItem.rightBarButtonItem = rightBarButton

func buttonClicked(_ button: UIBarButtonItem) { ... }