如何将数据从先前的序列传递到子视图控制器? [英] How to pass data to a child view controller from a previous segue?
问题描述
我需要从View Controller to a child of a parent view controller.
prepareSegue
不会传递数据.
我需要在viewdidload之前通过它.
i need to have it passed before viewdidload.
这是我试图将信息从View Controller传递给父级孩子的方式.
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
如果要从父级传递给子级视图控制器,则只需从父级设置childViewController的属性.
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];
选项2
或者,您可以设置一个代表人
Or, you can set up a delegate
步骤1 :在ChildViewController.h文件的接口上方设置协议
Step 1: set up protocol above interface in ChildViewController.h file
@protocol ChildViewControllerDelegate
- (NSDictionary *) giveMeData;
@end
@interface .....
第2步:在ChildViewController.h接口中创建委托属性
Step 2: create delegate property in ChildViewController.h interface
@property (strong, nonatomic) id<ChildViewControllerDelegate>delegate
步骤3 :在ParentViewController.h中声明委托协议
Step 3: declare delegate protocol in ParentViewController.h
@interface ParentViewController : UIViewController <ChildViewControllerDelegate>
第4步:在ParentViewController.m中添加此方法:
Step 4: in ParentViewController.m add this method:
- (NSDictionary *) giveMeData {
NSMutableDictionary * dataToReturn = [[NSMutableDictionary alloc]init];
dataToReturn[@"some"] = @"random";
dataToReturn[@"data"] = @"here";
return dataToReturn;
}
步骤5 :在启动childViewController之前,请声明委托属性.
Step 5: before launching childViewController declare delegate property.
childViewController.delegate = self;
[self presentViewController:childViewController animated:YES completion:nil];
步骤6 :在子视图控制器中,只要您想添加数据
Step 6: in child view controller whenever you want data add this
NSMutableDictionary * dataFromParent = [self.delegate giveMeData];
parentVC将运行'giveMeData'并返回NSMutableDictionary(根据您想要的任何数据进行调整)
The parentVC will run 'giveMeData' and return a NSMutableDictionary (adjust for whatever data you want)
这篇关于如何将数据从先前的序列传递到子视图控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!