不调用AppDelegate中的didSelectViewController

时间:2012-07-29 22:41:24

标签: iphone objective-c xcode delegates uitabbarcontroller

这就是我告诉didFinishLaunchingWithOptions有关在故事板中创建的标签栏控制器的方法。它现在在主选项卡中显示iAd横幅。但是当我点击其他标签时没有任何反应。永远不会调用didSelectViewController。如何将didSelectViewController连接到我的TabBarController并将currentController属性分配给当前/活动选项卡?

#import "AppDelegate.h"

@interface AppDelegate()

@property (nonatomic, retain) ADBannerView *bannerView;
@property (nonatomic, assign) UIViewController<BannerViewContainer> *currentController;

@end

@implementation AppDelegate

@synthesize window = _window;
@synthesize bannerView;
@synthesize currentController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch

    CGRect screenBounds = [[UIScreen mainScreen] bounds];

    // bannerView was here

    // This is the reference to the tab bar controller and first tab from storyboard.
    UITabBarController *tabController = (UITabBarController *)self.window.rootViewController;
    self.currentController = [[tabController viewControllers] objectAtIndex:0];

    NSLog(@"Root: %@", self.window.rootViewController);
    NSLog(@"Tab with banner: %@", self.currentController);

    return YES;
}

//and this isn't called:

- (void)tabController:(UITabBarController *)tabController didSelectViewController:
(UIViewController *)viewController
{
    // If called for selection of the same tab, do nothing
    if (currentController == viewController) {
        return;
        }
    if (bannerView.bannerLoaded)  {
     // If we have a bannerView atm, tell old view controller to hide and new to show.
        [currentController hideBannerView:bannerView];
        [(UIViewController<BannerViewContainer>*)viewController showBannerView:bannerView];
        }
        // And remember this viewcontroller for the future.
    self.currentController = (UIViewController<BannerViewContainer> *)viewController;

}

3 个答案:

答案 0 :(得分:9)

如你所知,你需要设置UITabBarController的代表 - 添加第三行,如下所示:

// This is the reference to the tab bar controller and first tab from storyboard.
UITabBarController *tabController = (UITabBarController *)self.window.rootViewController;
tabController.delegate = self;

通过这样做你做了什么:@interface AppDelegate : UIResponder <UIApplicationDelegate, ADBannerViewDelegate, UITabBarControllerDelegate>说,“我的类AppDelegate符合UITabBarControllerDelegate的协议”。但是,标签栏控制器实例还不知道您的类。因此,您必须告诉标签栏控制器哪个AppDelegate实例是您希望它回拨的实例。您可以通过设置delegate属性来完成此操作。

希望这有助于:)

答案 1 :(得分:3)

您必须将标签视图控制器的delegate属性设置为AppDelegate,以便调用任何委托方法。

答案 2 :(得分:3)

如果您从x-code模板创建了标签栏应用程序;您需要在appdelegate.m中添加以下行

self.tabBarController.delegate=self;

这应该超出didFinishLaunchingWithOptions方法

中的以下行
[self.window makeKeyAndVisible];