UIBarButtonItem selector not working

后端 未结 2 1407
广开言路
广开言路 2020-12-21 13:56

I have a MainViewController embed in a Navigation Controller, as shown below:

And in MainViewController.swift, I added two UIBarButtonItem(left and right) progr

相关标签:
2条回答
  • 2020-12-21 14:13

    try with inside scope once

    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
    }
    

    handle the action as

    func onRightLeftClick(_ sender: UIBarButtonItem){
        if sender.tag == 1{
            // rightButton action
        }else{
            // leftButton action
        }
    }
    
    0 讨论(0)
  • 2020-12-21 14:27

    You can also just add the lazy keyword to the rightButton and leftButton class properties. That way, the UIBarButtonItem won't be instantiated (and the action selectors won't attempt to be resolved) until they are used inside the class. Doing it this way allows you to use the barButtonItems anywhere in the class (not just in the function they are declared in).

    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))
    
    0 讨论(0)
提交回复
热议问题