【问题标题】:ViewController Delegate视图控制器委托
【发布时间】:2012-06-27 11:30:04
【问题描述】:

是否可以从 appDelegate 访问 ViewController 的方法,就像可以使用以下代码逆向一样:?

AppDelegate *ad = (AppDelegate *) [[UIApplication sharedApplication] delegate];

当我尝试时

ViewController *vc = (ViewController *) [[UIApplication sharedApplication] delegate];

我收到一个错误...

谢谢!

【问题讨论】:

  • 您收到错误消息,因为您正在调用 ViewController 显然不是 ViewController。 (我说'显然'是因为如果它已经是AppDelegate,它就不可能是一个。)你可以做你想做的事情,但代码取决于视图控制器的创建方式。

标签: objective-c ios xcode uiviewcontroller uiapplicationdelegate


【解决方案1】:

在您的AppDelegate 中,假设viewController 是您的rootViewController,您可以通过以下方式获取堆栈中所有视图控制器的列表:

NSLog(@"List of current active view controllers:%@", self.viewController.navController.viewControllers);

在 viewControllers 中访问特定的视图控制器:

[[self.viewController.navController.viewControllers objectAtIndex:i] someMethodOfThatViewController]; 

【讨论】:

    【解决方案2】:
    ViewController *vc = (ViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    

    或者如果你的委托有属性

    YourAppDelegate *ad = (YourAppDelegate*)[UIApplication sharedApplication].delegate;
    ViewController *vc = ad.yourViewControllerProperty;
    

    【讨论】:

      猜你喜欢
      • 2021-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      • 1970-01-01
      • 2018-01-01
      相关资源
      最近更新 更多