ios - SwiftUI - 使用新页面更新页面视图控制器
问题描述
我正在构建一个托管在此处的公共存储库上的天气应用程序。
这个问题最重要的文件是PageView和RepresentedPageViewController。
我已经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
}
}
我的问题是,一旦完成,用户只能看到视图控制器的第一个城市。页面视图控制器仍然存在,因为用户仍然可以滑动,但只有一个城市(第一个)。我已经创建了结果的屏幕记录,您可以在此处查看。
解决方案
认为问题仍然存在于协调器中:
当您在 pageviewcontroller 中更新控制器时,parent
Coordinator 的属性保持不变(并且因为它是一个结构,所以他的所有属性)。所以你可以简单地在你的方法中添加这行代码updateUIViewController
:
context.coordinator.parent = self
另外,请记住pageViewController.setViewControllers
会发生动画,因此您必须将动画设置为false,或正确处理。
还有很多其他方法可以解决这个问题(我写了最直观的解决方案),重要的是要知道错误来自哪里。
推荐阅读
- android - 在 Android 应用程序中将 Locale 更改为 ARABIC 时出现问题
- corda - 请注册实体“net.corda.finance.schemas.CashSchemaV1”
- python - setuptools 中的 install_requires 是否可以在某些软件包没有明确的 yocto-recipe 的情况下工作
- angular - 只有在有效值之后,如何在 Rx 订阅中做某事?
- android - 使用多个关键字搜索数据库的 sqlite 查询
- linux - CronTab 每 5 分钟重启一次不起作用
- c# - 通知所有消费者消息
- android - 平板电脑容器android中的片段显示问题
- css - 在一个组件中修复 mat-fab 按钮
- c# - 从 db RESTful Web API 最佳实践中传递日期