开发者

How to move the root controller into another controller

Suppose I have tested a navigation controller at the root level.

- (void)applicationDidFinishLaunching:(UIApplication *)application  
{  
    self.window.rootViewController = self.navController;   //iOS4  
}

Now I want to move it into one tab inside a tab controller (in a large开发者_JS百科r app). I feel I should be able to do an equivalent to the above:

self.rootViewController = self.navController;    //pseudocode

inside say

- (void)viewDidLoad

just dropping the code in. What in fact is the correct/elegant way to go about this? Often books refer to the root controller of a controller, and I'm wondering how to access it as I can the one of the window. (It's possible my understanding of this is misplaced of course).


Revised answer:

You can indeed insert your main UIViewController's view elsewhere in the UI as desired.

The trick is to do it early enough, and/or in the correct fashion. viewDidLoad isn't the correct place -- by the time that method is called, you usually want your main UIViewController implementation(s) to be in place.

There are two very good places to do this sort of UI setting up:

1) Via interface builder (nib files)

2) By implementing loadView in your UIViewController (do read the Apple docs -- very good info there).

It's one or the other, don't try do both at the same time for one UIViewController!

So in your example, you could use interface builder to edit a nib containing a tab bar controller. Drag in a plain UIViewController as a child of the tab controller, and then edit the 'Class' property of the UIViewController to MySpecialViewController (i.e. your subclass of UIViewController). And that's it, your nib now causes your view controller to be added to the UI inside a tab.

To taking approach 2), you'd want to set the viewControllers property of the UITabBarController in your loadView method of the UIViewController that contains the tab bar controller UI.

(My original answer below)

There isn't a consistently named way to access the root view controller(s) across Apple's provided view controllers (such as UINavigationController etc.). But the docs give you the info about how to access them; e.g. the UINavigationController has a property called viewControllers which you can access.

Ripping out existing view controllers willy-nilly and inserting them in different places in your UI is really not a very good idea. You could end up with all kinds of grief if you go down that round (e.g. device orientation changes). It's not the sort of approach Apple want you to take.

A better approach is to have several different instances of the view controller you want in different places. If they need access to the same data, they share the same data source. But they're individual, different instances.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜