首页 > 解决方案 > SwiftUI - 使用新页面更新页面视图控制器

问题描述

我正在构建一个托管在此处的公共存储库上的天气应用程序。

这个问题最重要的文件是PageViewRepresentedPageViewController

我已经UIPageViewController通过UIViewControllerRepresentable. 它允许用户在不同的城市中滑动并查看每个城市的天气数据,就像苹果的天气应用程序一样。当makeUIViewController我的页面视图控制器的方法被调用时,我设置了它的视图控制器(在这种情况下有 3 个开始,每个代表一个城市):

pageViewController.setViewControllers([controllers[0]],
                                          direction: .forward,
                                          animated: false)

这很好用,我可以在不同页面之间导航(滑动)。

在应用程序的搜索菜单中,用户可以点击他们想要获取天气的新城市。这会将新城市添加到应用程序的城市数据源中,页面视图控制器使用该数据源为每个城市创建页面。

因为保存城市的数据对象是有状态的,所以在设置该对象时(当用户添加新城市时)重新计算 UI。这会触发updateUIViewController页面视图控制器中的方法。在这个方法中,我重置了页面视图控制器的视图控制器(现在有 4 个,因为用户添加了一个新城市):

func updateUIViewController(_ uiViewController: UIPageViewController, context: UIViewControllerRepresentableContext<RepresentedPageViewController>) {

    // Check that the view controllers of the page view controller need to be reset.
    // This is true when a user has added a new city because we'll create a new 
    // view controller to be added to the page view controller. We perform this check because 
    // we don't want to reset the viewcontrollers in all cases where the updateUIViewController method is called.
    if shouldResetControllers {
        uiViewController.setViewControllers([controllers[0]],
                                            direction: .forward,
                                            animated: false)
        shouldResetControllers = false
    }
}

我的问题是,一旦完成,用户只能看到视图控制器的第一个城市。页面视图控制器仍然存在,因为用户仍然可以滑动,但只有一个城市(第一个)。我已经创建了结果的屏幕记录,您可以在此处查看。

标签: iosswiftswiftuiuipageviewcontroller

解决方案


认为问题仍然存在于协调器中:

当您在 pageviewcontroller 中更新控制器时,parentCoordinator 的属性保持不变(并且因为它是一个结构,所以他的所有属性)。所以你可以简单地在你的方法中添加这行代码updateUIViewController

context.coordinator.parent = self

另外,请记住pageViewController.setViewControllers会发生动画,因此您必须将动画设置为false,或正确处理。

还有很多其他方法可以解决这个问题(我写了最直观的解决方案),重要的是要知道错误来自哪里。


推荐阅读