Search code examples
iphoneiosobjective-cios5ios6

Pass Data to Subview


How can I pass data to a subview?


SubviewViewController.h:

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

TableViewController.m:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Load SubView    
    SubviewViewController *SVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SubviewViewController"];

    SVC.lblName.text = @"TEST"; // It's not working properly.

    SVC.view.frame = CGRectMake(20, 60, SVC.view.frame.size.width, SVC.view.frame.size.height);
    [self addChildViewController: SVC];
    [SVC didMoveToParentViewController:self];
    [self.view addSubview:SVC.view];
}

Solution

  • SVC.lblName.text = @"TEST"; wont work as the label is not yet initialised. the reason being that the view which is having the label is not loaded into the memory until [self.view addSubview:SVC.view]; and hence the lblName would be nil... so how to fix that??

    moving this line SVC.lblName.text = @"TEST";below [self.view addSubview:SVC.view]; will fix the issue of property initialisation as when SCV.view is added as subview the lblName will be assigned the property/outlet..

    hope this would work for you if everything else is paired correctly in ur code.