无法从ImageView访问TabBarController
我有一个在tabbar控制器中有一个导航控制器的应用程序。 导航控制器的根是一个表视图控制器。 表格视图有一个segue到图像视图。 我想更新图片视图控制器中的标签上的徽章值。 从标签栏控制器,这工作正常:
UIViewController *viewController = [self.tabBarController.viewControllers objectAtIndex:1]; viewController.tabBarItem.badgeValue = @"x";
但是,当我把相同的代码到imageview控制器,它不起作用。 执行后检查'viewController'的值时,值为零。 self.tabBarController也一样。 出于某种原因,图像视图控制器不能看到它的tabbarcontroller。
所以有很多方法可以做到这一点,但最好的办法是订阅一个NSNotification,然后从你的图像视图或任何地方做出这样的通知,所以它看起来像。
[[NSNotificationCenter defaultCenter] addObserver:objectToListen selector:@selector(methodToRun:) name:@"NotificationName" object:nil];
然后在你更深的项目,如ImageView或任何你张贴这样的
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationName" object:nil userInfo:dictionaryWithValuesForMethodToUse to use];
然后你从userInfo中获取信息,就像你在改变徽章值的方法一样
- (void)methodToRun:(NSNotification *)notification { NSDictionary *dictionary = [notification userInfo]; }
你应该可以通过self.navigationController.tabBarController访问tabBarController。 所以你的代码需要是:
UIViewController *viewController = [self.navigationController.tabBarController.viewControllers objectAtIndex:1]; viewController.tabBarItem.badgeValue = @"x";