UIBarButtonItem 选择器不工作

UIBarButtonItem selector not working

我在导航控制器中嵌入了一个 MainViewController,如下所示:

并且在 MainViewController.swift 中,我以编程方式添加了两个 UIBarButtonItem(左和右):

class MainViewController: UIViewController {

    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
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @objc func onRightClick() {
        print("[Main] Right Click")
    }

    @objc func onLeftClick() {
        print("[Main] Left Click")
    }
}

按钮确实显示在屏幕上,但有趣的是,选择器函数 onLeftClickonRightClick 永远不会在我按下左键或右键时被调用。有什么我应该做的才能让它发挥作用吗?我正在使用 Xcode 9.3。

尝试一次内部范围

override func viewDidLoad() {
    super.viewDidLoad()

    let rightButton = UIBarButtonItem(title: "Right", style: .plain, target: self, action: #selector(self.onRightLeftClick(_ :)))
    rightButton.tag = 1
    let leftButton = UIBarButtonItem(title: "Left", style: .plain, target: self, action: #selector(self.onRightLeftClick(_ :)))
    rightButton.tag = 2
    self.navigationItem.rightBarButtonItem = rightButton
    self.navigationItem.leftBarButtonItem = leftButton
}

将动作处理为

func onRightLeftClick(_ sender: UIBarButtonItem){
    if sender.tag == 1{
        // rightButton action
    }else{
        // leftButton action
    }
}

您也可以只将 lazy 关键字添加到 rightButton 和 leftButton class 属性。这样,UIBarButtonItem 将不会被实例化(并且动作选择器不会尝试解析),直到它们在 class 中被使用。这样做允许您在 class 中的任何地方使用 barButtonItems(不仅仅是在它们声明的函数中)。

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))