首页 > 解决方案 > 委托从模态呈现的视图控制器传回数据

问题描述

假设我们有两个视图控制器,一个带有标签的父级和一个带有表格视图的模态呈现的子级。如何使用委托将用户在表格视图中的选择传递回父级?

视图控制器1:

   var delegate: vc2delegate?

   override func viewDidLoad {
        super.viewDidLoad()
        let label.text = ""
   }

视图控制器2:

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
           return 5
       }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! Cell
            let selections = ["1", "2", "3", "4", "5"]
            cell.selections.text = selections[indexPath.row]
            return cell
       }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) as? Cell {
            cell.didSelect(indexPath: indexPath as NSIndexPath)

            }

        dismiss(animated: true, completion: nil)
        } 
   //wherever end of class is

   protocol vc2delegate {
      // delegate functions here
   }

我什至有正确的方法吗?我从来没有真正理解过这种模式,我认为学习 iOS 对我来说至关重要。另一个棘手的警告可能是 viewDidLoad() 在您关闭模态视图控制器时不会被调用。

标签: iosswiftprotocolsmodalviewcontrollerdelegation

解决方案


查看 UIViewController 生命周期文档: ViewDidLoad 只被调用一次。

有很多关于如何做到这一点的指南,只需快速搜索即可。您需要更新 dataSource 逻辑,因为我添加了一个快速字符串数组,并且您很可能会有一些更复杂的东西,但想法仍然相同。

顺便说一句,我使用了你的 vc1/vc2 命名约定,但我希望你的控制器有更有意义的名称。

在您的代码中,您在错误的 VC 上有委托。这是它应该是什么样子的快速代码示例:

class VC1: UIViewController {

    let textLabel = UILabel()

    // whenever you're presenting the vc2
    func presentVC2() {
        var vc2 = VC2()
        vc2.delegate = self
        self.present(vc2, animated: true, completion: nil)
    }
}

extension VC1: VC2Delegate {
    func updateLabel(withText text: String) {
        self.textLabel.text = text
    }
}


protocol VC2Delegate: class {
    func updateLabel(withText text: String)
}

class VC2: UIViewController {
    weak var delegate: VC2Delegate?
    let dataSource = ["string 1", "tring 2"]
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let string = dataSource[indexPath.row]
        self.delegate?.updateLabel(withText: string)
        dismiss(animated: true, completion: nil)
    }
}

推荐阅读