aircraft
aircraft

Reputation: 26924

How to add action to UIBarButtonItem which is created by storyboard in swift?

Create a UIBarButtonItem which name is nextVc on my navigationBar, and set its action by nextVc.action = #selector(self.gotoVC4), but it does not work.

my code is below:

    class ViewController3: UIViewController {

    @IBOutlet weak var nextVc: UIBarButtonItem!

    override func viewDidLoad() {
        super.viewDidLoad()

        nextVc.action = #selector(self.gotoVC4)

    }

    func gotoVC4() -> Void {


        print("go to vc4")

        let vc4 = ViewController4()
        self.navigationController!.pushViewController(vc4, animated: true)

    }


}

and the image of storyboard is here:

the storyboard shootscreen

Upvotes: 1

Views: 1623

Answers (2)

Paulw11
Paulw11

Reputation: 114975

Since you have a storyboard, simply ctrl-drag from the bar button to the "View Controller 4" scene to create a segue. No code needed.

Upvotes: 1

slashdot
slashdot

Reputation: 630

  1. You can omit self in selector expression
  2. Method should be dynamic or @objc

    override func viewDidLoad() {
        super.viewDidLoad()
    
        nextVc.action = #selector(gotoVC4)
    }
    
    dynamic func gotoVC4() -> Void {
        print("go to vc4")
    
        let vc4 = ViewController4()
        self.navigationController!.pushViewController(vc4, animated: true)
    }
    

Upvotes: 0

Related Questions