3

我目前有一个带有标签栏和多个视图控制器的 iPhone 应用程序。所有的视图都是在 Interface Builder 中设计的。我希望能够从视图控制器中获取标签栏当前选定的索引,但由于某种原因,此属性返回(null)。

我在视图控制器的 viewDidLoad 函数中调用了以下内容:

self.tabBarController.selectedIndex

这样做的正确方法是什么?

更新了 AppDelegate 类的代码。

MyAppDelegate.h

#import <UIKit/UIKit.h>

@interface MyAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> {
  UIWindow *window;
  UITabBarController *tabBarController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;

@end

MyAppDelegate.m:

#import "MyAppDelegate.h"

@implementation MyAppDelegate

@synthesize window, tabBarController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
  [window addSubview:tabBarController.view];
}

- (void)dealloc {
    [tabBarController release];
    [window release];
    [super dealloc];
}

@end
4

2 回答 2

4

您应该在 appDelegate 类中有一个指向标签栏的指针。您的视图没有标签栏,因此您从 [self.tabBarController selectedIndex] 收到 nil。

于 2009-10-27T12:46:11.940 回答
0

我想我明白了。使用以下返回正确的索引:

  MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(@"%d", appDelegate.tabBarController.selectedIndex);

应用程序崩溃的原因是我在 NSLog 部分使用了 %@ 而不是 %d 。我可以发誓我之前尝试过 %d,奇怪...

现在返回索引,但只返回一次。在您点击选项卡部分后,将返回一个索引编号,但当您再次点击另一个部分时,不会打印任何编号。可能是因为视图已经加载过一次。有没有办法解决这个问题?

于 2009-10-27T16:05:07.313 回答