【问题标题】:Swift Navigation Bar item not calling actionSwift 导航栏项目未调用操作
【发布时间】:2016-12-27 19:15:14
【问题描述】:

我在导航栏上有一个调用动作的项目。它停止工作。我已将项目与操作断开连接并重新连接。还是没有动作。该动作附加在情节提要中。如何调试或解决此问题?

【问题讨论】:

  • 你将不得不给我们更多。你怎么知道 IBAction 停止触发?尝试将print("Action called") 作为函数的第一行,看看是否有效
  • 是的,我已经这样做了,并且还在函数中放置了一个中断并且它不会中断

标签: swift uibutton navigation


【解决方案1】:

试试这样的

如果你有参数

 override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "ButtonName", style: .done, target: self, action: #selector(YourViewController.yourAction(_:)))

}

无参数

 override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "ButtonName", style: .done, target: self, action: #selector(YourViewController.yourAction))

}

【讨论】:

    【解决方案2】:

    如果您使用拖放功能创建 IBAction 方法,请确保它为按钮而不是“条形按钮项”创建方法。

    最简单的检查方法是在 Storyboard 中打开“文档大纲”视图。

    【讨论】:

      【解决方案3】:

      关键点是您的问题中的 target 参数。

      如果你不设置target: self,你就没有机会知道你从你的类中调用的方法是否有效。您要触发的选择器方法会表现得很奇怪,有时会起作用,有时会不起作用。

      您必须将 self 属性设置为您的 target 参数。不是nil

      代码中的示例用法:

      // trigger func, used from #selector
      @objc func selectorMethod() { /*...*/ }
      
      // create the button you wanna set
      let rightButton = UIBarButtonItem(title: "ButtonTitle", style: .plain, target: self, action: #selector(selectorMethod))
      
      // set the button item to the right bar
      navigationItem.rightBarButtonItem = rightButton 
      

      【讨论】:

        猜你喜欢
        • 2015-10-16
        • 1970-01-01
        • 2020-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多