1

斯威夫特3/Xcode 8.1

以下代码...

class PageContentVC: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate{

    var array = [String]()
    var currentIndex = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        array = ["1","2","3","4"]

        self.dataSource = self
        self.delegate = self
        self.setViewControllers([helperFunction(index: currentIndex)], direction: .forward, animated: true, completion: nil)

    }

    func helperFunction(index: Int) -> UIViewController{


        let newVC = storyboard?.instantiateViewController(withIdentifier: "PageContent") as! PageContent

        print("currentIndex is: \(currentIndex)")
        print("value at currentIndex is: \(array[currentIndex])")

        newVC.PageContentLabel.text = array[currentIndex]

        return newVC
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?{

        if (currentIndex ==  0) || (currentIndex == NSNotFound) {
            return nil
        }
        currentIndex -= 1
        return helperFunction(index: currentIndex)
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?{

        if (currentIndex == array.count - 1) || (currentIndex == NSNotFound) {
            return nil
        }
        currentIndex += 1
        return helperFunction(index: currentIndex) 
    } 
}

...在以下行中使用“Unexpectedly found nil while unwrapping an optional value”错误使应用程序崩溃:

newVC.PageContentLabel.text = array[currentIndex]

“PageContentLabel”肯定是通过界面生成器链接的,当我注释掉有问题的行时,应用程序运行良好。

我在这里想念什么?

4

2 回答 2

2

标签是nil因为您已经实例化了视图控制器,但是在故事板中定义的视图层次结构(如在 IB 中配置的那样)在相应的视图出现之前不会构建。您应该在视图控制器中添加一个字符串属性并helperFunction填充它,而不是IBOutlet. 然后,viewDidLoadofPageContent应该采用该字符串属性并使用它来设置text. 最重要的是,在被调用UILabel之前不要尝试使用插座。viewDidLoad

于 2016-11-21T21:52:15.540 回答
0

使用插座不是更简单吗?

@IBOutlet weak var PageContentLabel: UILabel!

ctrl 从情节提要中的 UILabel 拖动到类正下方的 PageContentVC 文件中,然后创建一个插座并为其命名任何您想要的名称。

于 2016-11-21T21:52:49.687 回答