When I click a certain list item in my UITableView, I want to pass the index of the item that I clicked on to the next detailed view.
This is my relevant code so far:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
HomeworkDetails *view = [[HomeworkDetails alloc] init];
int lastIndex = [indexPath indexAtPosition:[indexPath length] - 1];
NSLog(@"%u", lastIndex);
[self performSegueWithIdentifier: @"HomeworkDetailsSegue" sender:self];
view.currentIndex = lastIndex;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
At this point, I can successfully move on to the next ViewController (HomeworkDetails) but the information is not passed through. I am trying to accomplish this by doing view.currentIndex = lastIndex;
but this is not working. How else can I do this? Sorry if I missed anything; I am a beginner at iOS development.
With suggestions:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
HomeworkDetails *view = [[HomeworkDetails alloc] init];
int lastIndex = [indexPath indexAtPosition:[indexPath length] - 1];
NSLog(@"%u", lastIndex);
[self performSegueWithIdentifier: @"HomeworkDetailsSegue" sender:self];
view.currentIndex = lastIndex;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"HomeworkDetailsSegue"]) {
// note that "sender" will be the tableView cell that was selected
UITableViewCell *cell = (UITableViewCell*)sender;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; //**error**
HomeworkDetails *vc = (HomeworkDetails*)[segue destinationViewController];
vc.currentIndex = indexPath.row;
}
}
What you are describing can best be done in the prepareForSegue:sender:
method, instead of didSelectRowAtIndexPath:
. In your storyboard, make sure your HomeworkDetailsSegue
segue is set up between your tableView's prototype cell and the destination view controller.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"HomeworkDetailsSegue"]) {
// note that "sender" will be the tableView cell that was selected
UITableViewCell *cell = (UITableViewCell*)sender;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
HomeworkDetails *vc = (HomeworkDetails*)[segue destinationViewController];
vc.currentIndex = indexPath.row;
}
}
Also, as a matter of style, I would recommend renaming your HomeworkDetails class to HomeworkDetailsViewController. Doing this follows Apple's conventions more closely and makes it clearer what the class represents.
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