【问题标题】:Can't access TabBarController from ImageView无法从 ImageView 访问 TabBarController
【发布时间】:2012-11-24 23:58:14
【问题描述】:

我有一个在标签栏控制器中有导航控制器的应用。导航控制器的根是表视图控制器。表格视图与图像视图有一个segue。我想从图像视图控制器更新选项卡上的徽章值。从标签栏控制器,这工作正常:

UIViewController *viewController = [self.tabBarController.viewControllers objectAtIndex:1];
viewController.tabBarItem.badgeValue = @"x";

但是当我将相同的代码放入 imageview 控制器时,它不起作用。当我在执行后检查'viewController'的值时,该值为nil。 self.tabBarController 也一样。由于某种原因,图像视图控制器看不到它的 tabbarcontroller。

【问题讨论】:

  • 你使用什么样的 segue 从表格视图控制器转到图像视图控制器?
  • 它来自表格单元格。

标签: ios


【解决方案1】:

您应该能够使用 self.navigationController.tabBarController 访问 tabBarController。所以你的代码需要是:

UIViewController *viewController = [self.navigationController.tabBarController.viewControllers objectAtIndex:1];
viewController.tabBarItem.badgeValue = @"x";

【讨论】:

  • 这在图像视图控制器中不起作用。如果我在它执行后放置一个断点,viewcontroller 是 0x000000000
  • 我制作了一个具有您报告的结构的测试应用程序,它对我来说运行良好。如果你从图像视图控制器中记录 self.navigationController 和 self.navigationController.tabBarController,它们会给你什么?
  • 在 viewDidLoad 我放: NSLog(@"navigation controller: %@ tabbarcontroller: %@",self.navigationController,self.navigationController.tabBarController);日志输出:导航控制器:(null)tabbarcontroller:(null)当我在tableview的viewDidLoad中放入同一行时:导航控制器: tabbarcontroller:
  • @Bob 你确定你正在从你的表格视图单元格中进行推送吗?如果是,控制器必须有一个非空的 navigationController 属性。
  • 实际的控制器布局是tabbar -> navcontroller -> tableview -> tableview -> imageview
【解决方案2】:

所以有很多方法可以做到这一点,但最好的方法是订阅 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];
}

【讨论】:

  • 感谢您的想法。我会试一试。但我也想了解为什么我不能直接从图像视图中看到 tabbarcontroller.viewcontrollers 数组。
  • 没有从 uiimageview 到标签栏控制器的句柄。您需要给 uiimageview 一个委托。
  • 这很适合进行更新。我曾考虑使用协议,但我不明白如何在实现协议的类中设置委托属性。
猜你喜欢
  • 2019-10-31
  • 1970-01-01
  • 2014-01-27
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
  • 2017-01-06
  • 2017-06-28
  • 2015-03-11
相关资源
最近更新 更多