How to pass data to a child view controller from a

2019-02-20 12:38发布

I need to pass data from a View Controller to a child of a parent view controller.

prepareSegue isnt passing the data over.

i need to have it passed before viewdidload.

here is how im trying to pass info from a View Controller to a Child of a Parent.

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
   // NSLog(@"prepareForSegue: %@",segue.identifier);

    ViewController2 *transfer = segue.destinationViewController;

    if ([segue.identifier isEqualToString:@"Test"]) {
        transfer.testLabel = @"Pass this data";
    }
}

1条回答
Rolldiameter
2楼-- · 2019-02-20 13:42

Option 1

If you're passing from a parent to a child view controller, then just set the property of your childViewController from the parent.

customChildViewController.someRandomProperty = @"some random value";
[self presentViewController:customChildViewController animated:YES completion:nil];

Option 2

Or, you can set up a delegate

Step 1: set up protocol above interface in ChildViewController.h file

@protocol ChildViewControllerDelegate

- (NSDictionary *) giveMeData;

@end

@interface  .....

Step 2: create delegate property in ChildViewController.h interface

@property (strong, nonatomic) id<ChildViewControllerDelegate>delegate

Step 3: declare delegate protocol in ParentViewController.h

@interface ParentViewController : UIViewController <ChildViewControllerDelegate>

Step 4: in ParentViewController.m add this method:

- (NSDictionary *) giveMeData {
    NSMutableDictionary * dataToReturn = [[NSMutableDictionary alloc]init];
    dataToReturn[@"some"] = @"random";
    dataToReturn[@"data"] = @"here";
    return dataToReturn;
}

Step 5: before launching childViewController declare delegate property.

childViewController.delegate = self;
[self presentViewController:childViewController animated:YES completion:nil];

Step 6: in child view controller whenever you want data add this

NSMutableDictionary * dataFromParent = [self.delegate giveMeData];

The parentVC will run 'giveMeData' and return a NSMutableDictionary (adjust for whatever data you want)

查看更多
登录 后发表回答