Use didSelectRowAtIndexPath or prepareForSegue method for UITableView?
If you use prepareForSegue:sender:
then you won't have as much to change if you later decide to trigger the segue from some control outside the table view.
The prepareForSegue:sender:
message is sent to the current view controller, so I'd suggest something like this:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Assume self.view is the table view
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
DetailObject *detail = [self detailForIndexPath:path];
[segue.destinationViewController setDetail:detail];
}
In Swift:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let path = self.tableView.indexPathForSelectedRow()!
segue.destinationViewController.detail = self.detailForIndexPath(path)
}
I did this and it worked
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"Row Selected = %i",indexPath.row);
[self performSegueWithIdentifier:@"testID" sender:self.view];
}
When sender is UITableViewCell, you may ask UITableView to query indexPath of the cell.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let cell = sender as? UITableViewCell {
let indexPath = self.tableView.indexPathForCell(cell)!
assert(segue.destinationViewController.isKindOfClass(DetailViewController))
let detailViewController = segue.destinationViewController as! DetailViewController
detailViewController.item = self.items[indexPath.row] // like this
}
}