UIBarButtonItem: target-action not working?

后端 未结 11 917
无人及你
无人及你 2020-12-01 08:47

I\'ve got a custom view inside of a UIBarButtonItem, set by calling -initWithCustomView. My bar button item renders fine, but when I tap it, it doe

11条回答
  •  温柔的废话
    2020-12-01 09:37

    Swift 3 : Below is my full implementation for button customization and event handling.

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let button = UIButton.init(type: .custom)
        button.setTitle("Tester", for: .normal)
        button.setTitleColor(.darkGray, for: .normal)
        button.layer.borderWidth = 1
        button.layer.cornerRadius = 5
        button.layer.borderColor = UIColor.darkGray.cgColor
        button.addTarget(self, action: #selector(self.handleButton), for: .touchUpInside)
    
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        if let button = self.navigationItem.rightBarButtonItem?.customView {
            button.frame = CGRect(x:0, y:0, width:80, height:34)
        }
    }
    
    func handleButton( sender : UIButton ) {
        // It would be nice is isEnabled worked...
        sender.alpha = sender.alpha == 1.0 ? 0.5 : 1.0
    }
    

    Hope this helps

提交回复
热议问题