如何将数据从先前的 segue 传递给子视图控制器?
Posted
技术标签:
【中文标题】如何将数据从先前的 segue 传递给子视图控制器?【英文标题】:How to pass data to a child view controller from a previous segue? 【发布时间】:2015-12-19 08:32:15 【问题描述】:我需要从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";
【问题讨论】:
能否请您发布您的代码,然后我会尝试找出数据未通过的原因。问候,亚历克斯 我假设在将 segue 推送到父级时,您不能将数据从 VC 传递给父级 VC 的子级? @AlexWoe89 我用代码更新了我的问题 【参考方案1】:选项 1
如果您从父视图控制器传递到子视图控制器,则只需从父视图控制器设置您的 childViewController 的属性。
customChildViewController.someRandomProperty = @"some random value";
[self presentViewController:customChildViewController animated:YES completion:nil];
选项 2
或者,您可以设置委托
第一步:在 ChildViewController.h 文件中设置接口上面的协议
@protocol ChildViewControllerDelegate
- (NSDictionary *) giveMeData;
@end
@interface .....
第二步:在 ChildViewController.h 接口中创建委托属性
@property (strong, nonatomic) id<ChildViewControllerDelegate>delegate
第三步:在 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(根据您想要的任何数据进行调整)
【讨论】:
以上是关于如何将数据从先前的 segue 传递给子视图控制器?的主要内容,如果未能解决你的问题,请参考以下文章
将数据从一个视图控制器传递到下一个视图控制器,而无需在 swift 中进行 segue
使用 XLPagerTabStrip 将数据从父级传递给子级
如何使用自定义 UITableViewCell 进行 Segue?将数据传递到详细视图控制器的问题
如何在视图控制器之间传递数据而不在 ios 中使用 segue?