【问题标题】:UIBarButtonItem selector not workingUIBarButtonItem 选择器不起作用
【发布时间】:2019-11-28 18:38:08
【问题描述】:

我在 Navigation Controller 中嵌入了一个 MainViewController,如下所示:

在 MainViewController.swift 中,我以编程方式添加了两个 UIBarButtonItem(left 和 right):

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。

【问题讨论】:

    标签: swift selector uibarbuttonitem


    【解决方案1】:

    在内部范围内尝试一次

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

    【讨论】:

      【解决方案2】:

      您也可以将 lazy 关键字添加到 rightButton 和 leftButton 类属性。这样,UIBarButtonItem 将不会被实例化(并且操作选择器不会尝试解析),直到它们在类中使用。这样做可以让您在类中的任何地方使用 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))
      

      【讨论】:

      • 我已经编辑回答。没错,但不能让懒惰。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 2015-09-30
      相关资源
      最近更新 更多