如何在Swift中执行UIBarButtonItem的操作?

时间:2015-01-26 09:53:40

标签: swift uibarbuttonitem

如何在Swift中执行UIBarButtonItem的操作?我需要这个来编写测试。

我使用performSelector方法找到了Objective-C的an SO answer,但不幸的是,Swift无法使用它。

2 个答案:

答案 0 :(得分:2)

您可以通过向UIBarButtonItem添加操作来实现,也可以更改目标。

示例:

 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()
}

希望这有帮助。

答案 1 :(得分:0)

您可以使用sendAction中的sharedApplication - 方法。

UIApplication.sharedApplication()
    .sendAction(yourButton.action, to: yourButton.target,
                from: self, forEvent: nil)