Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpectedly found nil IBOutlet in prepareForSegue

Tags:

xcode

ios

swift

I have a detail view controller, and I would like to set the label text to a value taken from an array using an indexPath row.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if(segue.identifier == "showView"){
        let detailVC: DetailViewController = segue.destinationViewController as! DetailViewController
        let indexPath = self.MainTableView.indexPathForSelectedRow!
        detailVC.label.text = "Test"
        self.MainTableView.deselectRowAtIndexPath(indexPath, animated: true)
        }
}

I keep getting a fatal error: unexpectedly found nil while unwrapping an optional value. I have tried switching detailVC.label.text = "Test" to detailVC.label.text = names[indexPath.row] but I keep getting the same error every time.

I used the same lines of code for changing the cell's label text, with no errors, but for this label in the center of a blank view I cannot seem to get it right? Any thoughts on what needs to be changed?

By the way, the label in the detail view controller is @IBOutlet weak var label: UILabel!

like image 607
Mike Schmidt Avatar asked Dec 10 '22 16:12

Mike Schmidt


2 Answers

You cannot access IBOutlets of DetailViewController in prepareForSegue because they are not connected yet.

As mentioned in the comments create a String property in DetailViewController, set it in prepareForSegue and set the text property of the label in viewDidLoad or viewWillAppear of DetailViewController.

like image 188
vadian Avatar answered Jan 08 '23 13:01

vadian


The alternative is to call detailVC.loadViewIfNeeded() before setting the property. It will load all your IBOutlet's

like image 35
kasyanov-ms Avatar answered Jan 08 '23 13:01

kasyanov-ms