General way to pass data to UIViewControllers when using a UITabController

风流意气都作罢 提交于 2019-12-13 04:56:15

问题


I still haven't grasped this transfer with the structure below. I have read many posts, and have seen the same unanswered post by others, but no resolution.

I will try to simplify the question to make it easier for all.

The structure of the project is: UITabbar with tab1 and tab2

Tab1 has a Nav controller-->ViewController1

Tab2 has a Nav controller -->ViewController2

In viewcontroller1 (tab1) I have object X.

In ViewCOntroller2 (tab2) I want to display object X.

Don't worry about displaying, that's the easy part.

Question: How do you pass object X from tab1 to tab2. (what is the general pattern).

If you want to do it using prepareForSegue, is this ok, or is there a better way.

If using prepareForSegue, where do you drag the segue to?

  1. The tabbarcontroller

OR***** 2. to the second VC

Hopefully this is clear enough. With this in mind how would you perform the transfer?

Using the segue 1:

I tried doing this:

//(From View controller 1)

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
    if ([segue.identifier isEqualToString:@"CreateObjectXToDisplayObjectX"])

            ViewController2* vc2 = [[ViewController2 alloc] init];
            UITabBarController* tbc = [segue destinationViewController];
            vc2 = (ViewController2 *)[[tbc customizableViewControllers] objectAtIndex:1];
    //Crash here with with [MainNavigationControllerDesign setViewController1Delegate:]: unrecognized selector sent to instance 0x1064ef70'
            vc2.viewController1Delegate=self;
            vc2.objectXAtViewController2 = _objectXFromViewController1;
        }
    }

So, how is this Object X transfer accomplished? Thank you in advance


回答1:


You don't want to use segues in this way. Segues always instantiate new controllers when you go to them, but you already have these controllers embedded in the tab bar controller. If you were setting this up in code, I would say use a delegate, but if you set this up in IB, it's hard to do that. From VC2, you can get a reference to VC1's navigation controller with self.tabBarController.viewControllers[0]. VC1 will be that navigation controller's topViewController, so, putting that together, and adding a cast, you can access VC1 like this:

ViewController1 *vc1 = (ViewController1 *)[self.tabBarController.viewControllers[0] topViewController];

Once you have that reference, you can access any of vc1's properties. Don't forget to import ViewController1.h into ViewController2's .m file.



来源:https://stackoverflow.com/questions/14383156/general-way-to-pass-data-to-uiviewcontrollers-when-using-a-uitabcontroller

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