如何以编程方式在UITabBarController之间切换

时间:2011-03-01 09:42:43

标签: ios4 uitabbarcontroller uisegmentedcontrol

我有一个UITabBarController的应用程序,其中第一个选项卡包含HomePage的ViewController。我要做的是在标签之间切换(这很简单:[[self tabBarController] setSelectedIndex:index]),AND从“HomePage”导航到selectedTab的出口。

只是为了解释一下自己:TabElement1 ---> TabElementX ----> UISegmentedController:segmentY

问题是UISegmentedController是nil,因为它尚未初始化(至少在我第一次进行操作时)。我该如何解决这个问题?标签元素加载了笔尖。

编辑 - 这是一些代码:

@implementation HomeViewController    // Tab Indexed 0
// ...
- (void)playVideoPreview {
NSArray *array;
array = [[self tabBarController] viewControllers];
    // This is a test where I programmatically select the tab AND the switch.
[[[array objectAtIndex:2] switches] setSelectedSegmentIndex:1];
[[self tabBarController] setViewControllers:array];
}
@end

@implementation TGWebViewController    // Tab Indexed 2
// ...
@synthesize switches;    // In .h file: @property (nonatomic, retain) IBOutlet UISegmentedControl switches; Properly linked within the XIB.
- (IBAction)switchHasChangedValue {
    // Foo operations.
}

现在我第一次触发playVideoPreview我设法进入Tab Indexed 2,TGWebViewController,但是交换机还不存在,所以我发现自己的segmentedControl名为“switches”,选择了第一个段。如果我回到HomeViewController,然后我再次触发playVideoPreview,我得到了正确的行为。

1 个答案:

答案 0 :(得分:0)

我已经使用委托和布尔值修复了问题。现在,当TabBar的索引2处的ViewController加载完成时,它会向其委托发送一条消息,告知它必须选择哪个段。

编辑这是代码(希望它有帮助):

// Method in the first View that asks to tab the tab bar to launch the other
// view controller

- (void)playVideoPreview {
NSArray *array;

array = [[self tabBarController] viewControllers];
    if ( ![[array objectAtIndex:2] catSwitch] ) {
       [[array objectAtIndex:2] setDelegate:self];
       [[array objectAtIndex:2] setHasBeenLaunchedByDelegate:YES];
    } else {
       [self selectTab];
    }
    [[self tabBarController] setViewControllers:array];
    [[self tabBarController] setSelectedIndex:2];
}

// Now the operations performed by the second View Controller
- (void)somewhereInYourCode {
    if ( hasBeenLaunchedByDelegate ) {
        [[self delegate] selectTab];
    }
}

// In the First View Controller this is the delegate method, 
// launched from the Second View Controller
- (void)selectTab {
    NSArray *array;

array = [[self tabBarController] viewControllers];
    [[[array objectAtIndex:2] catSwitch] setSelectedSegmentIndex:[[bannerPreview pageControl] currentPage]];
}

// Some declaration
@protocol SecondViewControllerDelegate;
class SecondViewController : ViewController {
    id<TGWebViewControllerDelegate> delegate;
}
@end

@protocol SecondViewControllerDelegate 
    - (void)selectTab;
@end

// Meanwhile in the first view
class FirstViewController : ViewController <SecondViewControllerDelegate> {
// ...
}