本文介绍了如何在 UIPageViewController 中的两个 ViewController 之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 UIViewController,A 和 B,我将它们连接到一个 UIPageViewController 中:

I have two UIViewControllers, A and B, I connect them within a UIPageViewController:

这是它在故事板中的外观:

Here is how it looks in the Storyboard:

我不知道如何从 A 向 B 传递数据.

I don't know how to pass data to B from A.

推荐答案

假设您有一些类(您应该提供),例如:

Well assume you have some class (which you should have provided) like:

class MyModel {
    var dataFromFirstController: Any?
    var dataFromSecondController: Any?
    var sharedData: Any?
}

现在您需要一个页面视图控制器的子类,它是控制数据的一个子类,因此覆盖视图确实加载以创建模型:

Now you need a subclass of page view controller which is the one that controls the data so override view did load to create a model:

var myModel: MyModel!

override func viewDidLoad() {
    super.viewDidLoad()
    self.myModel = MyModel()
}

现在,当您生成或获取视图控制器时,您只需将相同的模型分配给它们:

Now when you generate or fetch view controllers you simply assign the same model to them:

func getFirstViewController() -> UIViewController {
    let controller = MyFirstController.generate()
    controller.myModel = self.myModel
    return controller
}

func getSecondViewController() -> UIViewController {
    let controller = MySecondController.generate()
    controller.myModel = self.myModel
    return controller
}

现在所有 3 个视图控制器共享相同的模型.这可能是最简单的方法,但有很多方法.最干净的可能是使用委托,它会向页面控制器报告,然后向给定的视图控制器报告.

Now all 3 view controllers share the same model. This is probably the easiest way of doing it but there are very many ways. The cleanest is probably using delegates which would report back to page controller that would then report back to given view controllers.

这篇关于如何在 UIPageViewController 中的两个 ViewController 之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:01