UIPageViewController访问错误

时间:2016-07-18 20:43:06

标签: ios swift uipageviewcontroller

我知道错误意味着我有一个NULL指针,但我不确定为什么这样,我认为它必须是我在我的代码中做错了。我的索引从1开始,因为我希望它在作为主页的中间视图控制器中启动。我正在尝试使页面视图控制器在类似于Snapchat的视图控制器之间滑动。我有以下代码:

import UIKit

class PageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {

  var viewControllersArray = [UIViewController]()
  var pageIndex: Int?
  let selectedIndex = 1

  override func viewDidLoad() {
    super.viewDidLoad()

    self.view.backgroundColor = UIColor.clearColor()

    let vc1 = storyboard?.instantiateViewControllerWithIdentifier("ProfileView") as! ProfileViewController
    let vc2 = storyboard?.instantiateViewControllerWithIdentifier("HomeView") as! HomeViewController
    let vc3 = storyboard?.instantiateViewControllerWithIdentifier("MatchesView") as! MatchViewController

    viewControllersArray.append(vc1)
    viewControllersArray.append(vc2)
    viewControllersArray.append(vc3)

    self.dataSource = self

    let pageContentViewController = self.viewControllerAtIndex(selectedIndex)
    self.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)  //Error here

  }

错误发生在这一行:

self.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)  //Error here

错误如下:"线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x7fff58d57ff8)

这是我的viewControllerAtIndex函数:

func viewControllerAtIndex(index : Int) -> UIViewController? {
   if((self.viewControllersArray.count == 0) || (index >= self.viewControllersArray.count)) {
     return nil
   }

   let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! PageViewController
   pageContentViewController.pageIndex = index


   return pageContentViewController
}

这是我的故事板,其中视图控制器可以在之间滑动:

enter image description here

非常感谢任何和所有帮助!

1 个答案:

答案 0 :(得分:1)

看起来像是

func viewControllerAtIndex(index : Int) -> UIViewController? {
   if((self.viewControllersArray.count == 0) || (index >= self.viewControllersArray.count)) {
     return nil
   }

   let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! PageViewController
   pageContentViewController.pageIndex = index


   return pageContentViewController
}

需要:

func viewControllerAtIndex(index : Int) -> UIViewController? {
   if((self.viewControllersArray.count == 0) || (index >= self.viewControllersArray.count)) {
     return nil
   }

   return viewControllersArray[index]
}

此外

let selectedIndex = 1

应该是

let selectedIndex = 0

因为1将引用第二页。