如何向 swift 中故事板创建的 UIBarButtonItem 添加动作?

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

在我的 navigationBar 上创建一个名为 nextVcUIBarButtonItem,并通过 nextVc.action = #selector(self.gotoVC4) 设置其动作,但它不起作用。

我的代码如下:

    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)

    }


}

故事板的图片在这里:

  1. 您可以在 selector 表达式中省略 self
  2. 方法应该是dynamic或者@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)
    }
    

由于您有故事板,只需按住 Ctrl 键并从栏按钮拖动到 "View Controller 4" 场景即可创建一个转场。无需代码。