How to set target and action for UIBarButtonItem at runtime

后端 未结 11 1965
小蘑菇
小蘑菇 2020-12-15 02:44

Tried this but only works for UIButton:

[btn setTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
11条回答
  •  独厮守ぢ
    2020-12-15 03:10

    If you need this enough times in your code, it's nice to go ahead and extend UIBarButtonItem which I've done below in Swift. :)

    import UIKit
    
    extension UIBarButtonItem {
        func addTargetForAction(target: AnyObject, action: Selector) {
            self.target = target
            self.action = action
        }
    }
    

    As an example, with self as a UIViewController, you'd simply call:

    self.myBarButtonItem.addTargetForAction(self, action: #selector(buttonPressed(_:))
    

提交回复
热议问题