【问题标题】:How to check who sent the message inside the IBAction如何在 IBAction 中检查谁发送了消息
【发布时间】:2021-11-02 23:13:37
【问题描述】:

我想将此 IBAction 函数用作通用函数

@IBAction func test(_ sender: Any) {
}

我怎么知道发送者是 UIButton?

【问题讨论】:

  • 好吧,您可以随时测试sender is UIButtonif let button = sender as? UIButton。但是,从代码可读性的角度来看,将动作用作通用函数是一个坏主意。理想情况下,每个按钮都应该有自己的处理程序。在某些情况下,可以为不同的按钮重用相同的函数,但为完全不同的操作重用相同的处理程序是没有意义的。
  • 已解决,谢谢@Sulthan
  • 如果让按钮=发件人为? UIButton { }

标签: ios swift


【解决方案1】:

您可以为每个按钮设置不同的标签。然后测试哪个标签作为发送者,就知道点击了哪个按钮。

@IBAction func test(_ sender: Any) {
    if let tag = (sender as? UIView).tag {
        switch tag {
        :/ add case for each tab value
        }
    }
}

【讨论】:

    【解决方案2】:

    试试这个

        @IBAction func test(_ sender: Any) {
            if let button = sender as? UIButton {
                // Do something with button
            }
            
            // If you don't use the button
            if sender is UIButton {
                // Do something
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      • 2019-06-27
      相关资源
      最近更新 更多