如何从以前的segue传递数据到子视图控制器?

我需要将数据从View Controller to a child of a parent view controller.

prepareSegue传递数据。

我需要在viewdidload之前传递它。

这是我试图将信息从视图控制器传递给父的子。

 -(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

如果您从父视图传递到子视图控制器,则只需从父视图设置childViewController的属性。

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

选项2

或者,您可以设置委托

步骤1 :在ChildViewController.h文件中设置上面的接口协议

 @protocol ChildViewControllerDelegate - (NSDictionary *) giveMeData; @end @interface ..... 

第2步 :在ChildViewController.h接口中创建委托属性

 @property (strong, nonatomic) iddelegate 

第3步 :在ParentViewController.h中声明委托协议

 @interface ParentViewController : UIViewController  

第4步 :在ParentViewController.m中添加此方法:

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

第5步 :在启动childViewController声明委托属性之前。

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

第6步 :在子视图控制器中,只要你想要数据添加它

 NSMutableDictionary * dataFromParent = [self.delegate giveMeData]; 

parentVC将运行’giveMeData’并返回NSMutableDictionary(根据您想要的任何数据进行调整)