【问题标题】:Check for condition befor executing button selector在执行按钮选择器之前检查条件
【发布时间】:2021-03-09 12:42:49
【问题描述】:

我有多个具有不同功能的按钮,现在这些按钮应该在执行实际功能之前检查条件,我不会更改所有按钮的功能,如下所示:

@objc func btnAction(sender: UIButton) {
  if condition {
    runSomthing()
    return
  } else {
    run the actual btn action
  }
}

我需要将其提取到一个超类中,该超类可以在不更改当前按钮操作的情况下完成我所寻找的操作

有正确的方法吗?

【问题讨论】:

    标签: ios swift xcode uibutton


    【解决方案1】:

    其中一种解决方案是将所有按钮链接到同一个 IBAction,并使用按钮标记值执行相应的按钮功能。这可以防止在每个 IBAction 中进行条件检查。

      guard let button = sender as? UIButton else {
        return
        }
        
        if condition {
        runSomthing()
        return
        } else {
        switch button.tag {
        case 1:
        Perform operation A
        case 2:
        Perform operation B
        case 3:
        Perform operation C
        default:
        print("None")
        return
        }
        }
    
    

    也可以使用枚举代替标记值,以便更好地识别。我推荐了How to use one IBAction for multiple buttons in Swift?

    【讨论】:

      猜你喜欢
      • 2018-07-26
      • 1970-01-01
      • 2021-04-21
      • 2013-03-28
      • 2021-09-03
      • 2012-11-17
      • 2018-06-23
      • 2014-05-22
      • 2021-06-06
      相关资源
      最近更新 更多