委托从模态呈现的视图控制器传回数据

Fus*_*ool 2 protocols delegation modalviewcontroller ios swift

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

视图控制器1:

   var delegate: vc2delegate?

   override func viewDidLoad {
        super.viewDidLoad()
        let label.text = ""
   }
Run Code Online (Sandbox Code Playgroud)

视图控制器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
   }
Run Code Online (Sandbox Code Playgroud)

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

小智 6

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

有很多关于如何执行此操作的指南,只需快速搜索即可。当我添加一个快速字符串数组时,您需要更新数据源逻辑,并且您很可能会遇到更复杂的东西,但想法仍然是相同的。

顺便说一句,我使用了您的 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)
    }
}
Run Code Online (Sandbox Code Playgroud)