Vikram
Vikram

Reputation: 11

All IBOutlets in a view controller are nil

All IBOutlets are nil in my View Controller. I don't know why it is happening

I get the following error:

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

I have used this code to set the variable finalScore from another controller:

let resultController = ResultsViewController()

resultController.finalScore = score
          
navigationController?.pushViewController(ResultsViewController, animated: true)
import UIKit

class ResultsViewController: UIViewController {
    
    @IBOutlet var imageView: UIImageView!
    @IBOutlet var titleLabel: UILabel!
    @IBOutlet var scoreLabel: UILabel!
    
    var finalScore = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if finalScore <= 2 {
            titleLabel.text = "Better Luck Next Time..."
            imageView.image = UIImage(named: "fail")
        } else {
            titleLabel.text = "Nice!!"
            imageView.image = UIImage(named: "pass")
        }
        
        scoreLabel.text = "Score: \(finalScore)"
        
    }
}

I am getting an error on this line: this is the image

It even shows the outlets are nil here: this is the image

How do I fix this?

Upvotes: 0

Views: 978

Answers (3)

Marcus
Marcus

Reputation: 1

In my case it was a missing checkmark in FileInspector -> Target Membership.

Upvotes: 0

Vikram
Vikram

Reputation: 11

I have found the problem and fixed it. The problem was in the other ViewController, I created an instance of the ResultsViewCotnroller class. I removed it and replaced it with:


let storyboard = UIStoryboard(name: "Main", bundle: nil)
let customViewController = storyboard.instantiateViewController(withIdentifier: "CustomViewController") as!CustomViewController

vadian's comment helped me to do so

Upvotes: 0

finebel
finebel

Reputation: 2355

You should open your Storyboard, select the ViewControler, go to the left pane and get to the Connections Inspector. There you should see a warning for the Outlets. You should remove the Outlet here by clicking on the little x next to it. Delete the Outlets also in code and then add them again.enter image description here

So the problem is, that you cannot just delete Outlets or Actions in code. You have to remove them also in the Connections Inspector.

Upvotes: 0

Related Questions