Search code examples
iosuitableviewuistoryboardsegue

IOS Segue- detecting table cell and opening a viewController


i am new to ios programming. i have a static tableViewController in which i have 3 cells. i have another view controller where there is a label and description. what i am trying to do is detect the cell which user clicks and then change the label which is in my second view controller according to that but the problem is whenever i click the cell the program crashes and added the breakpoint

here is my code

 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
      NSString *name;
      NSString *description;

    if([[segue identifier] isEqualToString:@"PushAppDetailsFromCell1"] )
    {
        name = @"Label 1 ";
        description = @"Long description of Label 1...";
    }

    else if([[segue identifier] isEqualToString:@"PushAppDetailsFromCell2"] )
    {
        name = @"Label 2";
        description = @"Long description of Label 2...";

    }
    else if([[segue identifier] isEqualToString:@"PushAppDetailsFromCell3"] )
    {
        name = @"Label 3";
        description = @"Long description of Label 3...";
    }
        else {
            return;

}
        AppDetailsViewController *apDetailsViewController = 
        segue.destinationViewController;  //here i am getting the breakpoint
        apDetailsViewController.appDetails =
        [[AppDetails alloc] initWithName:name description:description];

}

AppDetails.m

-(id)initWithName:(NSString *)name description:(NSString *)descr{

    self = [super init];

    if(self){
        self.name = name;
        self.description = descr;

        }
    return self;
}

AppDetailsViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.nameLabel.text = self.appDetails.name;
    self.descriptionLabel.text = self.appDetails.description;

}

Solution

  • NSArray *names = @[@"Label 1", @"Label2", @"Label 3"];
    NSArray *descs = @[@"Description 1", @"Description", @"Description 3"];
    
    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        if ([segue.identifier isEqualToString:@"PushAppDetailsSegue"]) {
             NSIndexPath *indexPath = [self.yourTableView indexPathForSelectedRow];
            AppDetailsViewController *controller = segue.destinationViewController;
            controller.appDetails = [[AppDetails alloc] initWithName:names[indexPath.row] description:descs[indexPath.row]];
        }
    }
    

    Drag a segue from your ViewController to SecondViewController and name it "PushAppDetailsSegue".