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

我在viewcontroller的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
有帮助吗?

解决方案

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

其他提示

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

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

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

现在返回索引,但只返回一次。点击选项卡部分后,将返回索引编号,但再次点击其他部分时,不会打印任何编号。可能是因为视图已经加载一次。有什么方法可以解决这个问题吗?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top