这里我在Swift中编写了UIPageViewController。这是工作。但是当我向前或向后滑动/滚动页面时,索引打印不正确。正确打开所需的页面。但是,此页面的索引值无法在控制台中正确打印。此外,有时它不会在滚动时打印索引,而页面正确打开。请帮助我在滚动时如何获得正确的页面索引。代码如下......
var pageViewController: UIPageViewController!
let pages = ["TabOneVc","TwoVC","ThreeVc","FourVc"]
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController?
{
if let index = pages.indexOf(viewController.restorationIdentifier!){
if index > 0{
print(index)
return viewcontrollerAtIndex(index - 1)
}
}
return nil
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController?
{
if let index = pages.indexOf(viewController.restorationIdentifier!){
if index < pages.count - 1{
print(index)
return viewcontrollerAtIndex(index + 1)
}
}
return nil
}
func viewcontrollerAtIndex(index: Int) -> UIViewController?
{
let vc = storyboard?.instantiateViewControllerWithIdentifier(pages[index])
print("index path",index)
return vc
}
答案 0 :(得分:0)
(当您浏览并降落在视图控制器上时,它还会加载下一个视图控制器,因此它已准备好,因此将再次调用viewControllerAtIndex并打印您当前所在的索引的下一个索引,从而导致问题错误的索引。)
实现当前索引的正确方法是实现此委托方法:
func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool){
检查transitionCompleted
是否为真(对于页面完全更改时),然后使用此方法根据当前代码获取当前索引:
let viewController = pageViewController.viewControllers![0] as! ViewController
let index = pages.indexOf(viewController.restorationIdentifier!)
这将获取pageViewController数组中的第一个视图控制器,并使用当前代码从restortationIdentifier获取其索引。
希望这有帮助。