Pass variable to view controller before viewDidLoad

故事扮演 提交于 2019-12-08 05:52:35

问题


I perform a segue which is defined in the Storyboard to open a new view controller. I need to configure the destination view controller of the segue in a special state where some of it's buttons does not needed to be displayed.

I know that I can do this by setting a variable on this controller in my source view controller's -prepareForSegue:sender:. The problem with this is, that firstly it instantiates the controller, so it's -viewDidLoad: will run, then only after can I set anything on it.

I can't create the controller entirely from code, because it's user interface is in Storyboard. -instantiateViewControllerWithIdentifier: also calls -viewDidLoad first obviously.

I could probably use a semaphore and add the initialization code into my destination controller's -viewWillAppear, but that's ugly, it has to be some more elegant way to do this than doing a check every time the view appears. (My settings need to be done only once.)

Is there some way to pass variables into the controller before it's -viewDidLoad runs?

EDIT: It looks like this happens only if I trigger the segue from code using -performSegueWithIdentifier:.


回答1:


On my machine and on iOS 8.0 and iOS 9.0, viewDidLoad is called after prepareForSegue. So, something like the following worked for my test case of your answer.

In your source controller:

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    TimViewController * controller = segue.destinationViewController;

    if( [controller isKindOfClass:[TimViewController class]] )
        controller.name = @"tim";
}

In your destination controller (TimViewController):

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do view setup here.

    NSLog( @"view did load %@", self.name );
}

Add a segue (a show segue) from your source control to the destination view controller.

Output:

2015-09-17 19:09:04.351 Test[51471:7984717] view did load tim



回答2:


I think there is some confusion here. -prepareForSegue:sender: gets called before -viewDidLoad gets called. Please double check your implementation.

Edit:

May be this thread will help you understand this and one of the mentioned cases fall in your case.



来源:https://stackoverflow.com/questions/32639850/pass-variable-to-view-controller-before-viewdidload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!