How to set target and action for UIBarButtonItem at runtime

后端 未结 11 2013
小蘑菇
小蘑菇 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:01

    Swift 5:

    Extract to extensions:

    extension UIBarButtonItem {
    
        static func nextBtn(target: AnyObject, action: Selector) -> UIBarButtonItem {
            let title = "Next"
            return button(title: title, target: target, action: action)
        }
    
        private static func button(title: String, target: AnyObject, action: Selector) -> UIBarButtonItem {
            return UIBarButtonItem(title: title, style: .done, target: target, action: action)
        }
    
    }
    

    Call in code:

    navigationItem.rightBarButtonItem = .nextBtn(target: self, action: #selector(rightBarButtonAction))
    

    Action:

    @objc func rightBarButtonAction() {
        Swift.print("Button tapped!")
    }
    

    Pretty easy to add new buttons to this factory.

提交回复
热议问题