Nick
Nick

Reputation: 71

UITableView Not Using Cell as Sender

enter image description hereI'm trying to segue and pass data (from UITableView to a UIViewController). My code is

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "IndividualAchievementsSegue" {
         let destination = segue.destinationViewController as? IndividualAchievementsViewController
        let cell = sender as! UITableViewCell
        let selectedRow = AchievementsTable.indexPathForCell(cell)!.row
         destination!.viaSegue = achievements[selectedRow]
        print(selectedRow)
    }
}

but the line let cell = sender as! UITableViewCell is throwing

Could not cast value of type 'ProgramName.AchievementsViewController' to 'UITableViewCell'

I have also tried

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "IndividualAchievementsSegue" {
         let destination = segue.destinationViewController as? IndividualAchievementsViewController
         let selectedRow = AchievementsTable.indexPathForSelectedRow!.row
         destination!.viaSegue = achievements[selectedRow]
        print(selectedRow)
    }
}

That fails because it finds nil unwrapping the optional during achievements[selectedRow] since that apparently gives me a nil from let selectedRow = AchievementsTable.indexPathForSelectedRow!.row

Upvotes: 0

Views: 91

Answers (2)

Nick
Nick

Reputation: 71

So the solution was to go into DidSelectrowAtIndexPath and remove DeselectRowAtIndexPath, which was in there twice by accident. Then use the following

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "IndividualAchievementsSegue" {
        let destination = segue.destinationViewController as? IndividualAchievementsViewController
        let selectedRow = AchievementsTable.indexPathForSelectedRow?.row
        destination!.viaSegue = achievements[selectedRow!]
        print(selectedRow)
    }
}

Upvotes: 0

Nirav D
Nirav D

Reputation: 72440

I think the problem is that your segue is connected with your AchievementsViewController to IndividualAchievementsViewController instead of UITableViewCell to IndividualAchievementsViewController. Check in the storyboard for that and correct the segue with TableCell to IndividualAchievementsViewController.

Upvotes: 1

Related Questions