ios - 从模态呈现的 View Controller 传回数据的委托(delegate)

标签 ios swift protocols modalviewcontroller delegation

假设我们有两个 View Controller ,一个带有标签的父 View 和一个带有 TableView 的模态呈现的 subview 。我如何使用委托(delegate)将用户在 TableView 中的选择传递回父级?

ViewController1:

   var delegate: vc2delegate?

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

ViewController2:

    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 对我来说至关重要。另一个棘手的警告可能是当您关闭模态视图 Controller 时不会调用 viewDidLoad() 。

最佳答案

看看 UIViewController 生命周期 docs : ViewDidLoad 只被调用一次。

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

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

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

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)
    }
}

关于ios - 从模态呈现的 View Controller 传回数据的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60677831/

相关文章:

iphone - 放在哪里||

ios - 如何为 oslog 创建的日志添加不同的记录器(输出目的地,如文件和 Crashlytics)?

ios - 为任何宽度类大小设置分段控制字体

java - 如何使用java byte[]准确发送如此复杂的十六进制、二进制协议(protocol)数据?

ios - 应用程序启动时令人费解的崩溃

ios - 无法从 Crashlytics 升级到 Fabric

ios - 核心绘图栏 - 仅几个栏的图例

ios - 导致 "self is immutable"错误的协议(protocol)扩展默认方法

swift - 在 Swift 中存储然后转换为元类型

ios - 我可以让 Realm Results 类使用协议(protocol)作为泛型吗?