【问题标题】:(Swift) Pass data into another viewController using callBack function(Swift) 使用回调函数将数据传递到另一个 viewController
【发布时间】:2020-05-30 06:06:48
【问题描述】:

情况:
我有一个包含许多单元格的 tableView。每个单元格都有相同的类型/类,每个单元格都有一个 toggleSwitch。
其中一个单元格,或者更准确地说是第 2 节第 0 行中的单元格,当它的开关被切换时,需要将 bool 类型的变量更新为 true/false(如果 switch 为 on => true)。该变量在第二个 VC 中。
使用下面的代码,点击哪个单元格无关紧要,它会打印switch is on/switch is off,但我只需要上面提到的单元格。
单元格的类:

@IBOutlet weak var labelCell: UILabel!

@IBOutlet weak var cellSwitch: UISwitch!

@IBAction func toggleSwitch(_ sender: Any) {
    if cellSwitch.isOn == true {
        print("switch is on")
    }
    else {
        print("switch is off")
    }
}

在 cellForRowAt 中:

case (2,0):
        cell.labelCell.text = "Shuffled"
        let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        let cardVC = (mainStoryboard.instantiateViewController(withIdentifier: "CardViewController") as! CardViewController)
        //place for condition, if switch is on/off, put the true/false to secondVC.shuffle
        cardVC.shuffle = true

我的问题是我的回调函数应该是什么样子,我对它们没有经验。以及如何检查这个(2,0)单元格是否被点击?

【问题讨论】:

  • 你什么时候展示你的CardViewController ?在 didSelectRowAt 中?
  • 不,在按钮上单击。按钮在tableView下
  • 您可以通过通知或委托模式解决此问题,或者将数据放入全局变量(单一事实来源)中,所有其他人都从该变量中获取数据。
  • 你有没有为此尝试过协议和委托?
  • 不,从来没有对他们做过任何事情。如果我没有找到解决方案,我会尝试。

标签: swift uitableview callback closures swift5


【解决方案1】:

在你的 tableViewCell 文件中声明这个回调函数,如下所示。

var callback:((Bool) -> Void)?

@IBAction func toggleSwitch(_ sender: Any) {
    if cellSwitch.isOn == true {
        print("switch is on")
        callback?(true)
    }
    else {
        print("switch is off")
        callback?(false)
    }
}


您可以使用 UITableViewDelegatedidSelectRowAt 方法获取行点击。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
if indexPath.section == 2 {
    if indexPath.row == 0 {
        // the tapped detect of (2,0)
    }
}
}

您可以从 cellForRowAt 方法中获取 UISwitch 的回调点击操作,如下所示。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   if indexPath.section == 2 {
      var cell = tableView.dequeueReusableCell(withIdentifier: "yourCell") as! YourCell
      if indexPath.row == 0 {
          //here you can write your callBack closure & your UISwitch's value will retrived here
          cell.callback = { [unowned self] check in
              cardVC.shuffle = check

          }
      }
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2016-07-26
    相关资源
    最近更新 更多