SwiftUI - 使用新页面更新页面视图控制器

4
我正在开发一款天气应用,其托管在公共存储库这里
对于此问题而言,最重要的文件是PageViewRepresentedPageViewController
我创建了一个与SwiftUI接口的UIPageViewController,通过UIViewControllerRepresentable使其与SwiftUI通信。它允许用户滑动浏览不同的城市并查看每个城市的天气数据,就像苹果的天气应用一样。当调用我的页面视图控制器的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
    }
}

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

2个回答

3

我认为问题在协调器中:

当您更新pageviewcontroller中的控制器时,协调器的parent属性保持不变(并且因为它是一个结构体,所有属性都是如此)。因此,您可以在updateUIViewController方法中添加以下代码:

context.coordinator.parent = self

请记住,pageViewController.setViewControllers的动画效果会发生变化,因此您需要将其设置为false或正确处理它。

还有许多其他解决方法(我写了最直观的解决方案),重要的是要知道错误的来源。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接