【问题标题】:Getting the name of a Controller获取控制器的名称
【发布时间】:2010-12-30 17:50:46
【问题描述】:

我有一个带有 TabBarController 的 iPhone 应用程序。我可以使用

访问当前的 ViewController
[appDelegate.myTabBarController selectedViewController]

但是我怎样才能得到这个控制器的名字呢?

例如,所选 ViewController 的名称是“TestViewController”。我怎样才能得到这个字符串/名称? 我想检查当前的 ViewController 是否为“TestViewController”。

非常感谢提前和最好的问候。

【问题讨论】:

    标签: iphone uiviewcontroller uitabbarcontroller


    【解决方案1】:

    你可以这样做:

    if([[appDelegate.myTabBarController selectedViewController] isKindOfClass:[TestViewController class]])
    {
    NSLog(@"Yes I am the controller you want.");
    }
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:
       if ([NSStringFromClass([[appDelegate.myTabBarController selectedViewController] class]) isEqualToString:@"TestViewController"])
      {
          //do your stuff here
      }
      

      【讨论】:

      • 你在比较字符串,所以你应该使用-[NSString isEqualToString:]。但这是不必要的。只需使用-[NSObject isKindOfClass:]
      • 当然,你是对的,但我只是在这里给出有用的函数 NSStringFromClass()
      • 同意弗朗西斯库。如果您不想将类#import 到要进行比较的类的 .h 中,比较类的字符串(名称)可能很有用。我有一种情况,我需要弄清楚正在展示哪个 VC。所以,我有一些代码告诉我 TopMostVC 是哪个。但为了执行 isKindOfClass,我需要将 VC 类纳入范围。
      【解决方案3】:

      你可以创建一个 UIViewController 类的子类并添加属性,例如

      @property(nonatomic, retain) NSString* name;
      

      然后使用name 属性将您的所有viewControllers 子类设为该类。然后只需在您的 -(id)init-(void)viewDidLoad 方法中设置控制器的名称,以便在需要时能够访问它。

      另一种方法是制作一些类名对的字典。像这样的东西

      [myDictionary setValue:stringClassName forKey:[MyViewController class]];
      

      让这个词典在整个应用程序中可用 - 如果这个类在您的词典中注册,您将能够随时获取每个类的名称。

      【讨论】:

        猜你喜欢
        • 2013-11-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-08
        • 2020-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-06
        相关资源
        最近更新 更多