Swift: label text --> “fatal error: unexpectedly found nil while unwrapping an Optional value”

后端 未结 5 1567
感情败类
感情败类 2021-01-17 20:10

like it says in the title, i am trying to change label text upon click of a button. Error appears at line self.playerChoice.text = \"You: Rock\"



        
5条回答
  •  無奈伤痛
    2021-01-17 20:55

    I ran into this problem and it turned out that the labels that I was trying to edit didn't exist at the time the code ran.

    Turns out I was referencing the same view controller from a parent view and a child container view. The labels I was trying to change were only in the container view but as both views loaded it ran the view controller for both so it tried to find the labels that didn't exist in the parent view and threw the above error.

    So the lesson I learned... If a reference to a view object is throwing a NIL..

    • The View isn't properly mapped to the View Controller.
    • The object within the view isn't mapped to the referencing IBOutlet.
    • Or as in my case, there are multiple views connected to the same View Controller and references to view objects in one view are not being found in the other.

提交回复
热议问题