- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"Action"]) { NSIndexPath *indexPath = [self.tbl indexPathForSelectedRow]; SecondViewController *destViewController = segue.destinationViewController; destViewController.getString = [getArray objectAtIndex:indexPath.row]; } }
i wanna to access the selected row index
,but show null
for every selected row. please help me?
add an 'indexPath` property to the custom table cell. initialize it in cellForRowAtIndexPath. move the tap handler from the view controller to the cell implementation. use the delegation pattern to notify the view controller about the tap event, passing the index path.
To create an IndexPath in objective C we can use. NSIndexPath *myIP = [NSIndexPath indexPathForRow: 5 inSection: 2] ; To create an IndexPath in Swift we can use.
You can get the indexPath of the last row in last section like this. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(numberOfRowsInLastSection - 1) inSection:(numberOfSections - 1)]; Here, numberOfSections is the value you return from numberOfSectionsInTableView: method.
Two cases:
Segue
connected from the viewController
Call segue
from your didSelectRowAtIndexPath
method, pass indexPath
as sender
-(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 and performSegueWithIdentifier:
.You can directly get sender
as UITableviewCell
in prepareForSegue: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]; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With