使用按钮更改PageViewController会使上一页的应用程序崩溃

时间:2019-05-19 15:51:19

标签: swift

我正在使用按钮来更改pagecontroll,但它发生了变化,但是问题出在最后一页,应用崩溃。这是我更改页面的代码

func backBtnClicked() {
        if currentIndex > 0 {
            currentIndex -= 1
        }
        if currentIndex < 1 {
            backBtn.isHidden = true
        }
        if currentIndex >= 0 {
            nextBtn.setTitle("Next", for: .normal)
            let startingViewController: TableVC? = viewControllerAtIndex(index: currentIndex)
            let viewControllers = [startingViewController]
            pageController?.setViewControllers(viewControllers as? [UIViewController], direction: .reverse, animated: false)
        }

    }

    @objc func nextBtnClicked() {
        if currentIndex != NSNotFound {
            currentIndex += 1
        }

        if currentIndex == pg.count - 1 {
            //Navigate Outside Pageview controller
            log("lastt")
        } else {


            let startingViewController: TableVC? = viewControllerAtIndex(index: currentIndex)
            let viewControllers = [startingViewController]
            pageController?.setViewControllers(viewControllers as? [UIViewController], direction: .forward, animated: false)
        }

    }

这是我得到的错误

  

由于未捕获的异常而终止应用程序   'NSInvalidArgumentException',原因:'视图控制器的数量   提供的(0)与请求的要求的数量(1)不匹配   过渡”

任何帮助

1 个答案:

答案 0 :(得分:0)

替换

pageController?.setViewControllers(viewControllers as? [UIViewController], direction: .forward, animated: false)

使用

pageController?.setViewControllers(viewControllers, direction: .forward, animated: false)

成为

let startingViewController = viewControllerAtIndex(index: currentIndex)!
pageController?.setViewControllers([startingViewController], direction: .forward, animated: false)

在后按

guard currentIndex - 1 >= 0 else { return }
currentIndex -= 1
// get the vc 

在下一次按下

guard currentIndex + 1 < pg.count else { return }
currentIndex  += 1
// get the vc

在您当前的代码中,似乎let startingViewController: TableVC?在某些时候返回nil,这使得此viewControllers as? [UIViewController]成为空数组

相关问题