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?

Screenshot: https://imgur.com/a/jA5wO

Answer Source

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

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

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