Cant pass value to another viewController?

五迷三道 提交于 2019-12-12 05:09:15

问题


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()

回答1:


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]
    }
}


来源:https://stackoverflow.com/questions/40113116/cant-pass-value-to-another-viewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!