Perform Segue after clicking on search result

2019-08-03 19:58发布

问题:

I try to to perform a segue to a subclass called "Detail Student" by clicking on the corresponding search result. Unfortunatelly it doesn't work. I cannot figure out why it doesn't work. Here is my code so far:

if (tableView == self.searchDisplayController.searchResultsTableView)
{student = [self.searchResults objectAtIndex:indexPath.row];
NSString *fullname = [NSString stringWithFormat:@"%@ %@", student.vorname, student.name];
cell.textLabel.text = fullname;
cell.detailTextLabel.text = student.hatBetrGrund.name;
    DetailStudent *controller = [self.storyboard instantiateViewControllerWithIdentifier :@"DetailStudent"];
    controller.delegate = self;
    controller.managedObjectContext = self.managedObjectContext;

   NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
   self.selectedStudent = [self.fetchedResultsController objectAtIndexPath:indexPath];

    controller.student = self.selectedStudent;
    NSLog(@"Wow");

}

回答1:

There are several things that are not clear in your code:

First, you are setting the text of text and detail labels. This belongs into cellForRowAtIndexPath or some other method like configureCell. However, selecting from a table view is caught via didSelectRowAtIndexPath. Make sure you configure your cell in one method and react to selection in another.

Second, you are instantiating your view controller but not presenting it. You can either

  • instantiate the view controller and present it via presentViewController:animated: or
  • link the detail view controller via a segue in storyboard. In this case, you do not need to instantiate it but simply call performSegueWithIdentifier. You configure your detail view in prepareForSegue.