How to get indexpath in prepareForSegue
Swift 3.0 / iOS 10
tableView.indexPathForSelectedRow
was introduced in iOS 9
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let indexPath = tableView.indexPathForSelectedRow{
let selectedRow = indexPath.row
let detailVC = segue.destination as! ParkDetailTableVC
detailVC.park = self.parksArray[selectedRow]
}
}
Two cases:
Segue
connected from theviewController
Call
segue
from yourdidSelectRowAtIndexPath
method, passindexPath
assender
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self performSegueWithIdentifier:@"Action" sender:indexPath]; }
Then you can get indexPath as sender in
prepareForSegue:sender:
method- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"Action"]) { NSIndexPath *indexPath = (NSIndexPath *)sender; SecondViewController *destViewController = segue.destinationViewController; destViewController.getString = [getArray objectAtIndex:indexPath.row]; } }
segue connected from the cell
No need to implement
didSelectRowAtIndexPath
method andperformSegueWithIdentifier:
.You can directly getsender
asUITableviewCell
inprepareForSegue:sender:
method.- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"Action"]) { NSIndexPath *indexPath = [self.tableView indexPathForCell:sender]; SecondViewController *destViewController = segue.destinationViewController; destViewController.getString = [getArray objectAtIndex:indexPath.row]; } }