Home > Blockchain >  When select cell to pass data always shows nil in the next ViewController using Swift
When select cell to pass data always shows nil in the next ViewController using Swift

Time:10-09

I am trying to pass data when select or press cell in TableView, it's working and I can print the result while select that cell. The problem when the second view shows the data is nil.

her is the code when when select cell:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedPlayer = feedItems[indexPath.row] as! UsersModel
    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
    let nextViewController = storyBoard.instantiateViewController(withIdentifier: "PlayersDetails") as! PlayersDetails
    nextViewController.name = selectedPlayer.name ?? "nil"
    print("Selcted \(selectedPlayer.name ?? "nil")")            
}

And her is the code in the second view:

override func viewDidLoad() {
    super.viewDidLoad()

    print("Name: \(name)")
    lbName.text = name
            
    // Do any additional setup after loading the view.
}

I tried to print from the second view but it shows nothing. What mistake I did?

Thanks

CodePudding user response:

You have to use pushViewController to take the data to next screen. Just add one more line in didSelectRowAt function as below:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedPlayer = feedItems[indexPath.row] as! UsersModel
    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
    let nextViewController = storyBoard.instantiateViewController(withIdentifier: "PlayersDetails") as! PlayersDetails
    nextViewController.name = selectedPlayer.name ?? "nil"
    print("Selcted \(selectedPlayer.name ?? "nil")") 
    self.navigationController?.pushViewController(nextViewController, animated: true)           
}

This will take your data to next screen.

CodePudding user response:

You can also try to execute "nextViewController.loadViewIfNeeded()"

Because you just created this ViewController, but did not present it, according to your hierarchical relationship, choose to use prensent or push to present it, it will execute "ViewDidload()"

  • Related