I am totally new at Swift so what follows may be a very basic question. Plus it's my first one at stackoverflow.com!
I am getting the "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" while setting text properties of UILabels in an instantiated view controller.
I am making a simple app to show a list of medicines i have at home and their expiry dates. A table view controller shows a list of the medicines, from an array called medArray, and when each one is tapped I want it to load a detail screen with some further details.
I set up a DetailView controller using IB and created the outlet connections of 3 UILabels:
// DetailView.swift
// HomeMed
//
// Created by Joao Boavida on 10/12/2018.
// Copyright © 2018 Joao Boavida. All rights reserved.
//
import UIKit
class DetailView: UIViewController {
@IBOutlet var nameLbl: UILabel!
@IBOutlet var subtextLbl: UILabel!
@IBOutlet var expdateLbl: UILabel!
}
I think the connections are successfully made as the dots on the left gutter are solid. I do get the error when tapping on a table view cell, which calls the following code:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let medicine = medArray[indexPath.row]
if let vc = storyboard?.instantiateViewController(withIdentifier: "DetailView") as? DetailView {
vc.nameLbl.text = medicine.name
if let subtext = medicine.subtext {
vc.subtextLbl.text = subtext
} else {
vc.subtextLbl.text = ""
}
let ISOdateFormatter = ISO8601DateFormatter()
ISOdateFormatter.formatOptions = [.withMonth, .withYear, .withDashSeparatorInDate]
vc.expdateLbl.text = "Exp: \(ISOdateFormatter.string(from: medicine.expiry))"
navigationController?.pushViewController(vc, animated: true)
}
}
I get the error as soon as I try to access vc.nameLbl.text, which is nil for reasons I don't know. vc.expdateLbl and vc.subtextLbl are also nil.
The "vc" view controller seems to be instantiated correctly because if I omit the configuration code and push it just after creating it it displays fine, albeit with the initial text in the labels that I set in IB. It is only when I try to change those labels that it crashes.
I have tried making and remaking the outlet connections with no success. Can anyone help troubleshooting this?
Thank you very much!