从app delegate设置标签栏徽章

时间:2015-02-19 21:32:27

标签: ios objective-c appdelegate

我的AppDelegate中有一个观察者,我希望用它在客户端收到新消息时在标签栏按钮上显示徽章编号。我可以使用此行SampleViewController.mviewDidLoad [[self navigationController] tabBarItem].badgeValue = @"1";修改徽章,但不知道如何从AppDelegate设置徽章。我尝试添加UITabBarDelegate,导入SampleViewController.h并致电[[SampleViewController navigationController] tabBarItem].badgeValue = @"1";,但无法正常工作。我还尝试在SampleViewController中实现一个类方法,它改变了徽章编号并从观察者那里调用,但是不能将[self navigationController] tabBarItem].badgeValue = @"1";放入类方法中。有人可以帮我解决这个问题吗?我知道我可以把观察者放到每个VC中,但是从AppDelegate做这个会更优雅。

AppDelegate.m

- (void)pubnubClient:(PubNub *)client didReceiveMessage:(PNMessage *)message {

   // DISPLAY A NUMBER IN THE TAB BAR BADGE WHEN THE CLIENT RECEIVES A MESSAGE

}

2 个答案:

答案 0 :(得分:2)

您可以使用简单的实现继承UITabBarController。然后你仍然可以发布NSNotifcation,但只需要一个类来观察它。我刚刚进行了这个测试:

@implementation AppDelegate


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

    [self performSelector:@selector(notify) withObject:nil afterDelay:5.0];

    return YES;
}

-(void)notify{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"post" object:nil];
}

//additional implementation...

你的自定义TabController

@implementation TabController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter ] addObserver:self selector:@selector(notify) name:@"post" object:nil];
}

-(void)notify{
    UITabBarItem *item = self.tabBar.items[0];
    item.badgeValue = @"1";
}

@end

显然,不要在自己的AppDelegate中使用performSelector。我只是这样做,所以我可以启动我的测试应用程序,验证标签栏上没有徽章,然后在5秒后观看它自动更新。您应该在适当的地方发布通知。

答案 1 :(得分:1)

您可以使用self.window.rootViewController来访问视图层次结构的根视图控制器。此时,通过遍历该层次结构来获取对所需视图控制器的引用。

相关问题