如何将数据传递给使用instantiateViewControllerWithIdentifier创建的ViewController?

时间:2013-07-25 10:23:20

标签: ios objective-c cocoa-touch

我创建了一个使用一堆Container视图的应用。今天我发现iOS 5不支持嵌入式segues(感谢Xcode让我知道。) 所以现在我有很多嵌入式segue,可以在彼此之间传递数据。

我正在使用此代码在UIView中加载ViewControllers而不是IB中的Container:

RootViewController的:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    NewsViewController *news = [storyboard instantiateViewControllerWithIdentifier:@"NewsViewControllerID"];
    news.view.frame = self.newsSection.bounds;
    [self.newsSection addSubview:news.view];
    [self addChildViewController:news];
    [news didMoveToParentViewController:self];
    // Do any additional setup after loading the view.
}

我如何使用上述内容并仍将数据传递给NewsViewController(类似于准备segue)

我尝试插入上面的内容

        NewsViewController *news = [storyboard instantiateViewControllerWithIdentifier:@"NewsViewControllerID"];
        news.view.frame = self.newsSection.bounds;
        news.myLabel.text = @"Test";
        [self.newsSection addSubview:news.view];

但标签不会改变。

我更喜欢传递数据而不使用单例或委托。

由于

3 个答案:

答案 0 :(得分:1)

问题可能是,在您设置标签文本时,标签仍为nil

尝试在NSString(例如labelText)和propertyNewsViewController中添加viewDidLoad self.myLabel.text = self.labelText;

答案 1 :(得分:1)

我建议您创建一个公共方法,从中可以在NewsViewController控制器上传递所需的数据。不过,现在的问题是你在初始化之前更新了UI。另外,我建议您查看如何创建内容UIViewControllers,因为现在您只添加了UIView。查看Apple的this文档,查看实现自定义容器视图控制器部分。而这部分代码:

- (void) displayContentController: (UIViewController*) content;
{
   [self addChildViewController:content];                 // 1
   content.view.frame = [self frameForContentController]; // 2
   [self.view addSubview:self.currentClientView];
   [content didMoveToParentViewController:self];          // 3
}

因此,在您的情况下,在完成第3步之后,您可以传递要在NewsViewController中使用的值。

答案 2 :(得分:-1)

你已经将你的下一个视图控制器和viewDidLoad传递给了字符串 它不起作用,因为你的视图尚未创建,如果检查UIlabel的实例,它将为零。因此,当您将文本加载到内存中时,您已将其设置在下一个viewcontroller中。

修改 你在NewsViewController中创建了一个NSString类型(textString)的属性变量,并将该字符串作为news.textString = @"Test";传递

并且NewsViewController的ViewDidLoad将该字符串设置为myLabel.text = textString;