swift - 如何正确地将数据从一个 View Controller 的选定单元格传递到前一个 View Controller ?

标签 swift uiviewcontroller tableview

假设我有两个名为 A 和 B 的 View Controller 。在我的 View Controller B 中有一个 TableView 。当我在我的表格 View 中选择一个单元格时,我想将该信息传递回 A。

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

myData = [String: DataModel]

其中 DataModel 采用以下形式

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

我想将 B 中所选单元格的 key 发送回 A。我应该怎么做?

谢谢你的帮助

最佳答案

  1. class BViewController 之前添加:

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

    weak var delegate: ClassBViewControllerDelegate?
    
  3. 实现 tableView 委托(delegate)方法 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. ClassAViewControllerClassBViewController 绑定(bind)到 ClassAViewController 中的适当位置,例如,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. ClassAViewController 中使用委托(delegate)方法 didSelectTableViewCell(onRow row: Int) 委托(delegate)契约(Contract) ClassBViewControllerDelegate :

    func didSelectTableViewCell(onRow row: Int) {
        print("Selected table view row is:", row)
    }
    

关于swift - 如何正确地将数据从一个 View Controller 的选定单元格传递到前一个 View Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51701029/

相关文章:

ios - 如何从 Swift 中的另一个类取消 NSURLSession?

ios - Avplayer 不播放来自 url 的视频

iphone - 旋转 UIView - willRotateToInterfaceOrientation 未被调用

ios - 从另一个类添加 View 作为 presentViewController 导致 UIEvents 不工作

ios - 通过代码更改搜索占位符

Xcode 6.1 : file was built for x86_64 which is not the architecture being linked (i386)

ios - 如何访问具有多个元素的字典键中的元素?

ios - 在 IOS 中的 tableview 顶部设置边距

ios - 未调用 IIViewDeckController 的中心 viewController 的 childViewController 上的 viewWillAppear

ios - 如何在不弄乱内容的情况下标记 dequeueReusableCell?