0

Since I was having issues creating a button via storyboard, I went about initiating a right nav bar button through code - found via this question How can I go back to the initial view controller in Swift?. This code is meant to take me back to my root view controller.

So here is the code as it stands at the moment.

 let button1 = UIBarButtonItem(image: UIImage(named: "HomeM25.png"), style: .plain, target: self, action: #selector(getter: UIDynamicBehavior.action))
    self.navigationItem.rightBarButtonItem  = button1

    func button() {
        self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
    }

I was under the impression that if I were to change the

action: #selector(getter: action)

I would be able to create a function following this button initialization like so

func action() {
        self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
    }

However, I am greeted with the "Use of local variable 'action' before its declaration'". I do not understand why this interpretation would not perform/why I would have to establish the action variable when its only use is a function name? Any help would be appreciated.

Update 1: Current Code

  override func viewDidLoad() {
    super.viewDidLoad()

    let button1 = UIBarButtonItem(image: UIImage(named: "HomeM25.png"), style: .plain, target: self, action: #selector(action))
    self.navigationItem.rightBarButtonItem  = button1

    func action() {
        self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
    }

Update 1: Also had to use a different function action to go back to the original view controller.

    self.navigationController!.popToRootViewController(animated: true)
jonpeter
  • 599
  • 8
  • 28

1 Answers1

0

It should be #selector(action). And you can define function within a function. Move action outside of the viewDidLoad function. Try this.

override func viewDidLoad() {
    super.viewDidLoad()
    let button1 = UIBarButtonItem(image: UIImage(named: "HomeM25.png"), style: .plain, target: self, action: #selector(action))
    self.navigationItem.rightBarButtonItem  = button1
}


func action() {
    self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
}
Bilal
  • 18,478
  • 8
  • 57
  • 72
  • You should be doing this in `viewDidLoad` function or any other function. Post complete code. – Bilal Aug 16 '17 at 03:24