Search code examples
iosuilabeluistoryboardsegue

What am i doing wrong in passing this string to label in a view controller segue (ios)?


I have a table view controller segueing (with identifier feedToPollQuerySeg) to another view controller. I am trying to print out the index number of the row selected in a label in the latter.

Feed View:

@interface FeedController3 : UIViewController <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, weak) IBOutlet UITableView* feedTableView;


-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(NSString*)stringNum{
        if([segue.identifier isEqualToString:@"feedToPollQuerySeg"]){


        PollQueryController *pqc = [[PollQueryController alloc] init];
        pqc = [segue destinationViewController];
        NSLog(@"This is row sending: %@", stringNum);
        pqc.parentRowSelected.text = stringNum;
        }

    }

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

            NSInteger rowSelected = indexPath.row;
            NSString *stringNum = [NSString stringWithFormat:@"%d", rowSelected];
            NSLog(@"This is row selected: %@", stringNum);
         [self performSegueWithIdentifier: @"feedToPollQuerySeg" sender: stringNum];

    }

PollQuery View

@interface PollQueryController : UIViewController <UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *parentRowSelected;


@implementation PollQueryController
@synthesize parentRowSelected;

-(void)viewDidLoad{
    [super viewDidLoad];

    NSLog(@"Parent Row Selected: %@", parentRowString);

...
}

But the label isn't updating...?

This is row selected: 1
This is row sending: 1
Parent Row Selected:

Solution

  • Its because when you are in prepareForSegue of FeedController3, PollQueryController's view isn't initialized. Add NSString in PollQueryController set NSString value in prepareForSegue.

    In viewWillAppear of PollQueryController assign text to parentRowSelected label.

    Like This -

    In the viewController that will present the another viewController:

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        if ([segue.identifier isEqual:@"feedToPollQuerySeg"])
        {
            PollQueryController *pvc = [segue destinationViewController];
            pvc.myString = stringNum;
        }
    }
    

    And inside the presented viewController:

    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
    
        self.parentRowSelected.text = self.myString;
    }