我的MainViewController
是我的 UIPageViewController 。我想要显示2个FirstDataViewController
和SecondDataViewController
的观看次数。
我想执行更新MainViewControllre
中项的请求,然后将其传递给我的2个子视图。
getData
是我的功能,其中包含来自请求的数据,然后更新MainViewController's
项
extension MainViewController {
func getData() {
getBasicData() { [weak self] (basicModel) in
guard let strongSelf = self else { return }
strongSelf.getExperienceData() { [weak self] (experienceModel) in
guard let strongSelf = self else { return }
let items = RequestItems(basicData: basicModel,
experienceData: experienceModel)
strongSelf.updateItems(items: items)
}
}
}
}
MainViewController:
class MainViewController: UIPageViewController {
var items: RequestItems
let firstDataViewController: FirstDataViewController
let secondDataViewController: SecondDataViewController
let basicDataManager: APIManagerProtocol
let experienceDataManager: APIManagerProtocol
private(set) lazy var orderedViewControllers: [UIViewController] = {
return [self.firstDataViewController, self.secondDataViewController]
}()
convenience init() {
self.init(with: RequestItems())
}
init(with items: RequestItems) {
self.items = items
let apiManager = APIManager()
basicDataManager = apiManager.createBasicDataManager()
experienceDataManager = apiManager.createExperienceDataManager()
self.firstDataViewController = FirstDataViewController(with: items)
self.secondDataViewController = SecondDataViewController(with: items)
super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
self.edgesForExtendedLayout = []
}
func updateItems(items: RequestItems) {
self.items = items
}
}
如何使用getData()
函数首先更新MainViewController项,然后将数据传递给子视图?或者也许有更好的选择来做到这一点?
答案 0 :(得分:0)
这不是一个好的解决方案。 “GetData”方法需要一些时间才能完全执行,因此您应该:
但我认为您的MainViewController是应用程序中的第一个控制器,因此您应该:
将完成块添加到“getData”方法中:
func getData(_ completion: [RequestItems] -> ()) {
getBasicData() { [weak self] (basicModel) in
guard let strongSelf = self else { return }
strongSelf.getExperienceData() { [weak self] (experienceModel) in
guard let strongSelf = self else { return }
let items = RequestItems(basicData: basicModel,
experienceData: experienceModel)
completion(items)
}
}
}
将“updateItems”方法添加到您的视图控制器(而不是在init方法中传递)
使用完成处理程序但在MainViewController init
之外调用“getData”方法init(with items: RequestItems) {
...
self.items = items
self.firstDataViewController = FirstDataViewController()
self.secondDataViewController = SecondDataViewController()
...
}
func viewDidLoad() {
super.viewDidLoad()
getBasicData { [weak self] (items) in
guard let strongSelf = self else { return }
strongSelf.updateItems(items)
strongSelf.firstDataViewController.updateItems(with: items)
strongSelf.secondDataViewController.updateItems(with: items)
}
}
func updateItems(items: RequestItems) {
self.items = items
}