开发者

Switch views on the same tab in a tab bar WITHOUT using a navigation controller

I am looking for a way to switch the current view in a tab container to another, all within the same tab and not using a navigation controller.

I have tried something like this:

FooViewController *fooViewController = [[FooViewController alloc] initWithNibName:@"FooViewController" bundle:nil];
self.view.window.rootVi开发者_如何学编程ewController.view.window.rootViewController = fooViewController;
[fooViewController release];

And this:

FooViewController *fooViewController = [[FooViewController alloc] initWithNibName:@"FooViewController" bundle:nil];
[self.view removeFromSuperview];
[self.view addSubview:fooViewController.view];
[fooViewController release];

To no avail.

Any ideas?


The method I used was to create a subclass of UIViewController that I used as the root view of 3 child view controllers. Notable properties of the root controller were:

  • viewControllers - an NSArray of view controllers that I switched between
  • selectedIndex - index of the selected view controller that was set to 0 on viewLoad. This is nonatomic, so when the setSelectedIndex was called it did all the logic to put that child view controller in place.
  • selectedViewController - a readonly property so that other classes could determine what was currently being shown

In the setSelectedIndex method you need to use logic similar to:

[self addChildViewController: selectedViewController];
[[self view] addSubview: [selectedViewController view]];
[[self view] setNeedsDisplay];

This worked really well, but because I wanted to use a single navigation controller for the entire application, I decided to use a different approach.

I forgot to mention you will want to clear child view controllers every time you add one, so that you don't stack up a ton of them and waste memory. Before the block above call:

for (UIViewController *viewController in [self childViewControllers])
    [viewController removeFromParentViewController];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜