简体   繁体   English

StoryBoard的ViewController使ViewDidLoad调用两次

[英]ViewController from StoryBoard make ViewDidLoad called twice

I would like to make (from my StoryBoard) a ViewController that I will be able to push from anywhere by code (this ViewController will be used a lot of time, so I don't wan't to add tons of segues in the StoryBoard...). 我想(从我的StoryBoard中)制作一个ViewController,我可以通过代码从任何地方推送它(这个ViewController将花费很多时间,所以我不想在StoryBoard中添加大量的segues ...)。

I also have to pass some variables from the current ViewController to the pushed one. 我还必须将一些变量从当前ViewController传递到推送的变量。 To do it I'm using this code : 为此,我使用以下代码:

NBItemDetailsViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"ItemDetailsViewController"];
vc.item = self.selectedItem;
[self.navigationController pushViewController:vc animated:YES];

It nearly works, but in the pushed ViewController, the viewDidLoad method is called twice. 它几乎可以工作,但是在推送的ViewController中,两次调用了viewDidLoad方法。 The first time, I can get the item, but the second, it is null. 第一次,我可以获得项目,但是第二次,它为null。 Of course it seems like the displayed ViewController is the one of the second call, and I can't get my item. 当然,似乎显示的ViewController是第二个调用之一,我无法获取我的商品。

Any idea ? 任何想法 ? Is there a better option, using segues in the StoryBoard (I can't believe there is no way to reuse a ViewController in the StoryBoard...) ? 在StoryBoard中使用segues是否有更好的选择(我无法相信没有办法在StoryBoard中重用ViewController ...)?

PS : I already tried to use viewDidAppear. PS:我已经尝试使用viewDidAppear。

You might create a subclass of UIViewController (MyRegularViewController) and assign a .xib by (MyRegularViewController.xib) 您可以创建UIViewController (MyRegularViewController)的子类,并通过(MyRegularViewController.xib)分配.xib

File > New > File > User Interface > Empty

and drag a UIViewController to your emtpy xib file. 并将一个UIViewController拖到您的emtpy xib文件中。 Associate your MyRegularViewController with that xib, then customize it. 将MyRegularViewController与该xib关联,然后对其进行自定义。

Now you can use it anywhere you want simply like this; 现在,您可以像这样简单地在任何地方使用它。

MyRegularViewController *regular = [[MyRegularViewController alloc] initWithNibName:@"MyRegularViewController" bundle:nil];
self.navigationController pushViewController:regular animated:YES];

You are not obligated to use storyboard in all cases, in fact using your storyboard for something like this situation will mess your storyboard. 您没有义务在所有情况下都使用情节提要,实际上,在这种情况下使用情节提要会弄乱您的情节提要。 Simply use a xib and a custom class for this. 只需为此使用一个xib和一个自定义类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM