NSLayoutConstraint: Found nil while unwrapping optional Value

左心房为你撑大大i 提交于 2020-01-06 01:52:20

问题


having a bit of a problem here, so I was trying to cal a function of which it will change the height constraint constant, but it gives me an error :

"NSLayoutConstraint: Found nil while unwrapping optional Value"

Another catch is I can change the constant from the ViewDidLoad() function without any errors, while calling the function from another controller gives me the error.

I tried to clean the project, delete the outlet and re-outlet it again. No luck.

Hope you can help me, thanks!

MainController

var bottomContainerCon: CGFloat = 80
@IBOutlet  var bottomContainerHeight: NSLayoutConstraint!
   override func viewDidLoad() {
    super.viewDidLoad()
   bottomContainerHeight.constant = bottomContainerCon
   }

    func changeHeight() {
    bottomContainerHeight.constant = self.bottomContainerCon 
    self.view.layoutIfNeeded()
 }

PagerController

    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = self.storyboard?.instantiateViewController(withIdentifier: "MainNeedPage") as! NeedDetailsController


    let currentIndex = pages.index(of: previousViewControllers.first!)!

    let nextIndex = abs((currentIndex + 1) % pages.count)


    if(nextIndex == 0) {
        vc.changeHeight(value:80)
    } else {
        vc.changeHeight(value:250)
    }


  override func viewDidLayoutSubviews() {
    self.bottomContainerHeight.constant = self.bottomContainerCon
    self.view.layoutIfNeeded()

}

Here's the storyboard Storyboard


回答1:


Since you instantiate the VC , then the outlet is nil until view loads

@IBOutlet  var bottomContainerHeight: NSLayoutConstraint!

you need to do this

var bottomContainerCon: CGFloat = 0

then assign the value inside

viewDidLoad / viewDidLayoutSubviews like this

bottomContainerHeight.constant = bottomContainerCon


来源:https://stackoverflow.com/questions/51651389/nslayoutconstraint-found-nil-while-unwrapping-optional-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!