0

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.

Community
  • 1
  • 1
Antoine
  • 1,782
  • 1
  • 14
  • 32

2 Answers2

2

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.

HamzaGhazouani
  • 6,464
  • 6
  • 33
  • 40
0

You can use the sendAction-method from sharedApplication.

UIApplication.sharedApplication()
    .sendAction(yourButton.action, to: yourButton.target,
                from: self, forEvent: nil)
Christian
  • 22,585
  • 9
  • 80
  • 106