How can I execute an UIBarButtonItem's action in Swift ? I need this to write tests.
I've found an SO answer for Objective-C, using the performSelector method, but unfortunately it's not available from Swift.
How can I execute an UIBarButtonItem's action in Swift ? I need this to write tests.
I've found an SO answer for Objective-C, using the performSelector method, but unfortunately it's not available from Swift.
You can do that by adding action to your UIBarButtonItem, you can also change the target.
Example :
 override func viewDidLoad() {
    super.viewDidLoad()
    let mySelector: Selector = "showActionAlert"
    let rightNavigationBarItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: mySelector)
    navigationItem.rightBarButtonItem = rightNavigationBarItem
}
func showActionAlert() {
    let alertView = UIAlertView(title: "MY ALERT", message: "barButtonItem Tapped", delegate: nil, cancelButtonTitle: "OK")
    alertView.show()
    navigationItem.rightBarButtonItem?.action = "showSecondAlert"
}
func showSecondAlert() {
    let alertView = UIAlertView(title: "MY ALERT", message: "My second alert", delegate: nil, cancelButtonTitle: "OK")
    alertView.show()
}
Hope this helps.
 
    
    You can use the sendAction-method from sharedApplication.
UIApplication.sharedApplication()
    .sendAction(yourButton.action, to: yourButton.target,
                from: self, forEvent: nil)
