I have a "Country" ViewController
with two ContainerViews
: Side Menu (TocVC
) and Data Screen (CountryDetailsVC
) on it. Button that controls Side Menu toggling is located in Navigation bar.
Side Menu has a TableView
and upon didSelectRowAt indexPath
I would like pass its String
value back to Data Screen and assign it to a Label
on it.
This is what I've tried:
TocVC
:
var selectedItem:String = ""
...
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedItem = contents[indexPath.row]
let VC = CountryDetailsVC()
VC.labelUpdate(dataFrom: selectedItem)
}
CountryDetailsVC
:
@IBOutlet weak var label: UILabel!
...
func labelUpdate(dataFrom: String) {
self.label.text = dataFrom
}
But I'm getting Fatal error: Unexpectedly found nil while unwrapping an Optional value
as I understand because TocVC
passed data but CountryDetailsVC
didn't "refresh" itself and run the function.
What is the right way to do what I'm trying to do?
EDIT: Storyboard screenshot Storyboard
EDIT1: Updated code.
Country
:
let detailsVc = CountryDetailsVC()
TocVC
:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedItem = contents[indexPath.row]
Country().detailsVc.labelUpdate(dataFrom: selectedItem)
CountryDetailsVC
:
@IBOutlet weak var label: UILabel!
func labelUpdate(dataFrom: String) {
print("dataFrom: \(dataFrom)")
self.label.text = dataFrom
}
The function prints out dataFrom
string to the console but crashes on the next line trying to assign dataFrom
to label.text
.
When I change label: UILabel!
to label: UILabel?
it doesn't crash but not changing text either.
Maybe it has something to do with this similar situation?
EDIT2: Updated code. Reference to self
in segue to TocVC
. Still doesn't work.
Country
:
let detailsVc = CountryDetailsVC()
...
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue .destination is TocVC {
let vc = segue.destination as? TocVC
vc?.countryVC = self
}
}
TocVC
:
var countryVC: Country?
...
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedItem = contents[indexPath.row]
Country().detailsVc.labelUpdate(dataFrom: selectedItem)
CountryDetailsVC
:
@IBOutlet weak var label: UILabel!
func labelUpdate(dataFrom: String) {
print("dataFrom: \(dataFrom)")
self.label.text = dataFrom
}