Denis Windover
Denis Windover

Reputation: 445

swift how to fix prepare for segue for table view

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "toChat2" {

        guard let navController = segue.destinationViewController as? UINavigationController,
        let chatController = navController.viewControllers.first as? ChatViewController else { return }

        let indexPaths = self.tableView!.indexPathsForSelectedRows! //crashes on this line
        let indexPath = indexPaths[0] as NSIndexPath

        chatController.senderId = FIRAuth.auth()?.currentUser?.uid
        chatController.senderDisplayName = FIRAuth.auth()?.currentUser?.displayName ?? ""
        chatController.friendId = messagesArray[indexPath.row].userId
        chatController.userName = messagesArray[indexPath.row].name
    }

what's the problem? I tried another way. I declare two variables and tried to act from here:

var userId:String!
var userName:String!      

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {

    userId = messagesArray[indexPath.row].userId
    userName = messagesArray[indexPath.row].name
    self.performSegueWithIdentifier("toChat2", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "toChat2" {

        guard let navController = segue.destinationViewController as? UINavigationController,
        let chatController = navController.viewControllers.first as? ChatViewController else { return }

        chatController.senderId = FIRAuth.auth()?.currentUser?.uid
        chatController.senderDisplayName = FIRAuth.auth()?.currentUser?.displayName ?? ""
        chatController.friendId = userId
        chatController.userName = userName
    }
}

But in this way it works but not correct, after clicking one of the items in table view without responding and only from second click it moves but with data from first click! :) how to fix it?

Upvotes: 2

Views: 223

Answers (2)

0ndre_
0ndre_

Reputation: 3631

That is because you are using didDeselectRow instead of didSelectRow in the second example :) . So change tableView(didDeselectRow) to tableView(didSelectRow) and the problem with sending the wrong data should be solved.

Hope it will help you.

Upvotes: 0

creeperspeak
creeperspeak

Reputation: 5523

I've done that before! You are using did DESELECT row instead of did SELECT row.

Either way, you should probably not force unwrap those variables in your prepare for segue. You can use another guard statement to get the indexPathsForSelectedRows. That way you won't crash, at least.

Upvotes: 1

Related Questions