【问题标题】:How to execute UIBarButtonItem's action in Swift?如何在 Swift 中执行 UIBarButtonItem 的动作?
【发布时间】:2015-01-26 09:53:40
【问题描述】:

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

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

【问题讨论】:

    标签: swift uibarbuttonitem


    【解决方案1】:

    您可以通过向 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()
    }
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2014-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-07
        • 2021-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多