gpt4 book ai didi

ios - 尽管在 IB 中链接,但标签仍为 nil

转载 作者:行者123 更新时间:2023-12-01 19:59:16 24 4
gpt4 key购买 nike

swift 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”肯定是通过界面生成器链接的,当我注释掉有问题的行时,应用程序运行良好。

我在这里想念什么?

最佳答案

标签是 nil因为您已经实例化了 View Controller ,但是 Storyboard中定义的 View 层次结构(如在 IB 中配置的那样)在出现相应 View 之前不会构建。您应该在 View Controller 中添加一个字符串属性并拥有 helperFunction填充它,而不是 IBOutlet .然后,viewDidLoadPageContent应该使用该字符串属性并使用它来设置 textUILabel .最重要的是,在 viewDidLoad 之前不要尝试使用网点。已被调用。

关于ios - 尽管在 IB 中链接,但标签仍为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40730007/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com