![](/img/trans.png)
[英]Passing Data From Parent View Controller to Child View Controller Swift 4
[英]How can I passing data from parent view controller to child view controller?
如何将数据从父视图控制器传递到子视图控制器?
我尝试与代表们这样做。 但我认为这不是一个选择吗?
如果您从父视图传递到子视图控制器,那么只需从父视图设置childViewController的属性。
customChildViewController.someRandomProperty = @"some random value";
[self presentViewController:customChildViewController animated:YES completion:nil];
或者,您可以设置委托
步骤1:在ChildViewController.h文件中设置上面的接口协议
@protocol ChildViewControllerDelegate
- (NSDictionary *) giveMeData;
@end
@interface .....
第2步:在ChildViewController.h接口中创建委托属性
@property (strong, nonatomic) id<ChildViewControllerDelegate>delegate
第3步:在ParentViewController.h中声明委托协议
@interface ParentViewController : UIViewController <ChildViewControllerDelegate>
第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(根据您想要的任何数据进行调整)
您可以通过以下方式访问子视图控制器:
NSArray *children = self.childViewControllers;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.