我有UIPageViewController
。我想在单击按钮时翻转页面。我想像viewControllerAfter
和viewControllerBefore
一样向前和向后翻页。我使用此代码来翻页,但无法正常工作:
@IBAction func nextAction(_ sender: Any) {
let pageController = self.storyboard?.instantiateViewController(withIdentifier: "PageViewController") as! UIPageViewController
pageController.dataSource = self
pageController.delegate = self
let firstController = getContentViewController(withIndex: 0)!
let secondController = getContentViewController(withIndex: 1)!
let contentControllers = [firstController, secondController]
pageController.setViewControllers(contentControllers, direction: .forward, animated: true, completion: nil)
}
如何解决?
更新
extension UIPageViewController {
func goToNextPage(animated: Bool = true) {
guard let currentViewController = self.viewControllers?.first else { return }
guard let nextViewController = dataSource?.pageViewController(self, viewControllerAfter: currentViewController) else { return }
setViewControllers([nextViewController], direction: .forward, animated: animated, completion: nil)
}
func goToPreviousPage(animated: Bool = true) {
guard let currentViewController = self.viewControllers?.first else { return }
guard let previousViewController = dataSource?.pageViewController(self, viewControllerBefore: currentViewController) else { return }
setViewControllers([previousViewController], direction: .reverse, animated: animated, completion: nil)
}
}
答案 0 :(得分:0)
首先,您必须具有活动的pageVC才能导航到特定的VC,而不是
pageController.setViewControllers(contentControllers, direction: .forward, animated: true, completion: nil)
您必须仅设置要导航为喜欢的vc
pageController.setViewControllers([firstController], direction: .forward, animated: true, completion: nil)
并跟踪它的索引,因此当用户再次滚动时,调用了dataSource方法以加载正确的VC,我创建了一个演示Here,其功能相同