![](/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.