0

I ran into some problems when adding barButtons and found the solution in the answer to another question, but the it didn’t explain why you must create and add the buttons in the same scope. I want to know why you can’t create the buttons in class level and add them in a method like viewDidLoad. Example code that doesn’t work from that question copied below:

let rightButton = UIBarButtonItem(title: "Right", style: .plain, target: self, action: #selector(onRightClick))
let leftButton = UIBarButtonItem(title: "Left", style: .plain, target: self, action: #selector(onLeftClick))

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.rightBarButtonItem = rightButton
    navigationItem.leftBarButtonItem = leftButton
}

This get an error that won’t recognize the @objc methods(not included here). There’s nothing wrong with those methods, as when you move the button-creations inside viewDidLoad the error disappears and the code works.

Antonia Zhang
  • 103
  • 11
  • What are the errors? – rmaddy Apr 26 '19 at 04:17
  • It doesn’t matter now because I know it’s because of accessing property before initializing, but I went through a few different error messages when trying to make it work. One of them is actually very indicative of the reason come to think of it. – Antonia Zhang Apr 26 '19 at 07:58
  • It may matter for others searching on the same issue. – rmaddy Apr 26 '19 at 08:00
  • I couldn’t get Xcode to show the error now, after I removed “lazy.” This happened the first time too. I get no error while the button just doesn’t work. – Antonia Zhang Apr 26 '19 at 08:14

2 Answers2

4

These bar button properties are created before init is called and you're trying to access class methods which can't be called before init is called.

If you want to initialize your buttons on class scope, you will have to make them lazy variables in order to create them when they are needed

lazy var rightButton = UIBarButtonItem(title: "Right", style: .plain, target: self, action: #selector(onRightClick))
lazy var leftButton = UIBarButtonItem(title: "Left", style: .plain, target: self, action: #selector(onLeftClick))
Robert Dresler
  • 10,580
  • 2
  • 22
  • 40
-1
     override func viewDidLoad() {
        super.viewDidLoad()

        let leftBarButton = UIBarButtonItem(title: "Left Button", style: .plain, target: self, action: #selector(pressOnleftBarButton))
        navigationItem.leftBarButtonItem = leftBarButton

        let rightBarbutton = UIBarButtonItem(title: "Right Button", style: .plain, target: self, action: #selector(pressOnRightBarButton))
        navigationItem.rightBarButtonItems = rightBarbutton
    }

    @objc func pressOnleftBarButton(){
      //Perform Action on Left Button
    }

    @objc func pressOnRightBarButton(){
        //Perform Action on right Button
    }
Deviyani Swami
  • 749
  • 8
  • 17