代码之家  ›  专栏  ›  技术社区  ›  John Doe

如何正确地将数据从一个viewcontroller的选定单元格传递到上一个viewcontroller?

  •  0
  • John Doe  · 技术社区  · 6 年前

    假设我有两个名为A和B的viewcontroller,在viewcontroller中有一个tableview。当我在tableview中选择一个单元格时,我希望将该信息传递回。

    我有一本字典,内容如下:

    myData = [String: DataModel]
    

    其中数据模型采用

    struct DataModel{
        var address = ""
        var name = ""
    }
    

    我想将B中选定单元格的键发送回A。我该如何继续?

    谢谢你的帮助

    3 回复  |  直到 6 年前
        1
  •  2
  •   naeemjawaid    6 年前
    1. 在此之前添加 class BViewController:

      protocol ClassBViewControllerDelegate: class {
          func didSelectTableViewCell(onRow row: Int)
      }
      
    2. 在中创建委托属性 BViewController :

      weak var delegate: ClassBViewControllerDelegate?
      
    3. 实现tableView委托方法 tableView(_:didSelectRowAt:)

      func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {
              let row = indexPath.row
              delegate?.didSelectTableViewCell(onRow: row)
      }
      
    4. 告诉 ClassAViewController 它符合 ClassBViewControllerDelegate 像这样的:

      class ClassAViewController: UIViewController, ClassBViewControllerDelegate {
      
    5. 捆绑 类AVIEWController ClassBViewController 在适当的地方 类AVIEWController 比如说, prepareForSegue:sender:

      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
          if segue.identifier == "SegueIdentifierXYZ" {
              if let vc = segue.destination as? ClassBViewController {
                  vc.delegate = self
              }
          }
      }
      
    6. 使用委托方法 didSelectTableViewCell(onRow row: Int) 委托合同 B类IEWControllerDelegate 在里面 类AVIEWController :

      func didSelectTableViewCell(onRow row: Int) {
          print("Selected table view row is:", row)
      }
      
        2
  •  0
  •   vivekDas    6 年前

    使用完成块或使用委托可以实现此目的。 使用块可以如下编码:

    在你的 B VC 为完成块创建一个属性。

    var cellSelectionCallBackHandler: ((DataModel, Int) -> Void)?
    

    设置 cellSelectionCallBackHandler 财产来源 VC A .

    VCObjectB.cellSelectionCallBackHandler = { (data, index) in
     // Use your data here
    }
    

    VC B 在选择这样的单元格时调用完成处理程序

    cellSelectionCallBackHandler?(yourData, index)
    

    有任何疑问请发表评论。

        3
  •  0
  •   Rizwan    6 年前

    可以使用委托方法来实现它。调用以解除B的位置/方法调用委托。您可以在中实现此委托。

    您还可以拥有一个单例数据处理程序类,在该类中,您可以设置和获取所需的属性,并可以从项目中的任何位置访问它。