Reputation: 1360
I have some text in tableview cells which you will tap on it you will pass the name of the cell and also you will be pushed to another view.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let row = indexPath.row
valueToPass = sections[row]
print(valueToPass)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "fromWelcomeToSectionPage") {
// initialize new view controller and cast it as your view controller
let vc:sectionPage = segue.destination as! sectionPage
vc.passedValue = valueToPass
}
}
also I created code in another controller to check
if passedValue == "Základy" {
print("it works")
}
This is how I trying to pass it. Variable valueToPass is global variable. Idk but when I'm printing it in didSelectRowAtIndexPath it's okey but in prepare it's nil.
After tapping on cell I've got unexpectedly found nil while unwrapping an Optional value
That's how I created variable in another view
var passedValue = String()
Upvotes: 0
Views: 123
Reputation: 9825
Your prepareForSegue
method is called before the didSelectRowAt
method, so you can't rely on any logic you do in didSelectRow
to help pass the data.
You can get the selected row in prepareForSegue
and use it there to get the data and pass it along:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "fromWelcomeToSectionPage") {
// initialize new view controller and cast it as your view controller
let vc = segue.destination as! sectionPage
let selectedRow = tableView.indexPathForSelectedRow!.row
vc.passedValue = sections[selectedRow]
}
}
Upvotes: 1