如何从AppDelegate.m访问tabBarController?

问题描述 投票:2回答:1

这是我的故事板:“

我正在尝试从AppDelegate.m中的方法访问tabBarController

这是AppDelegate.h:

#import <UIKit/UIKit.h>
#import <FacebookSDK/FacebookSDK.h>
#import "STAlertView.h"


@interface demo_AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, strong) STAlertView *av;

@end

这是AppDelegate.m:

#import "demo_AppDelegate.h"
#import "demo_Friends_ViewController.h"


@implementation demo_AppDelegate
-(void)showFriendReqAlert:(NSNotification *)pNotification{
    NSLog(@"Hello from showFriendReqAlert:");
    NSLog(@"Root: %@", [self.window.rootViewController.navigationController.tabBarController viewControllers]);

}
....
....
....
....
@end

[我的主要动机是当调用此方法showFriendReqAlert:时,在第三个选项卡栏项目Friends上显示一个红色标志。但是,每当我尝试选择tabBarItem时,它在NSLog中都显示为null。

我也尝试了以下方法:self.window.rootViewController.navigationController.tabBarControllerself.window.rootViewController.tabBarController

但没有任何作用。有帮助吗?

谢谢!

ios objective-c iphone xcode5
1个回答
7
投票

[我相信(很抱歉,在这里相信;;),TabBarController应该是您的第一个控制器,而您的navigationBarController必须随后出现,因为这对于navigationController(如果更改选项卡)并没有太大意义/ pop。

我建议您删除第一个DemoViewController和第二个NavigationController,并且第一个控制器是您的TabBarController(在IB中只需设置“是初始视图控制器”)。

然后您可以像这样访问tabBar

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    UITabBarController *tbc = (UITabBarController *)self.window.rootViewController;
}

Swift 5:

guard let tabBarController = window?.rootViewController as? UITabBarController else { return }
© www.soinside.com 2019 - 2024. All rights reserved.