iOS Swift如何从编辑页返回后重新加载UIPageViewController显示新增城市
最优实现方案
你不需要重建整个PageViewController,只需要在RootViewController的viewWillAppear生命周期方法中刷新PageViewController的缓存即可,整体改动极小,具体实现如下:
核心逻辑说明
UIPageViewController默认会缓存前后页的视图控制器,城市数据更新后它不会主动重新拉取数据源,你只需要重新设置一次当前展示的视图控制器,就能清空旧缓存,后续滑动时会自动读取最新的城市列表生成对应页面。
代码修改
直接替换RootViewController中的viewWillAppear方法即可:
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.isNavigationBarHidden = true // 同步最新的城市数据,兼容编辑页直接修改UserDefaults的场景 self.modelController.cities = self.modelController.defaults.stringArray(forKey: "SavedStringArray") ?? [String]() if self.modelController.cities.isEmpty || self.modelController.cities == [""] { self.modelController.cities = ["Current Location", "San Francisco", "New York"] } // 刷新PageViewController缓存,保持当前展示页面不变 guard let currentVC = pageViewController?.viewControllers?.first as? DataViewController, let currentIndex = modelController.indexOfViewController(currentVC), let targetVC = modelController.viewControllerAtIndex(currentIndex, storyboard: storyboard!) else { return } pageViewController?.setViewControllers([targetVC], direction: .forward, animated: false) }
可选扩展(按需使用)
如果你需要用户添加完城市后自动跳转到新增的城市页面,把上面代码里的currentIndex替换为modelController.cities.count - 1即可。
内容的提问来源于stack exchange,提问作者Björn
相关产品推荐
相关产品推荐

