【问题标题】:Identify UITabBarItems view controller instances the proper way以正确的方式识别 UITabBarItems 视图控制器实例
【发布时间】:2011-08-19 19:44:15
【问题描述】:

我有一个带有标签栏的应用程序,可以像这样打开不同的视图控制器:

firstViewController = [[UITableViewController alloc] init];
UINavigationController *firstNavigationController = [[UINavigationController alloc] initWithRootViewController:firstViewController];
[firstNavigationController setTabBarItem:[[UITabBarItem alloc] initWithTitle:@"Add" image:[UIImage imageNamed:@"Add.png"] tag:1]];

[viewControllers addObject:firstNavigationController];

secondViewController = [[UITableViewController alloc] init];
UINavigationController *secondNavigationController = [[UINavigationController alloc] initWithRootViewController:secondViewController];
[secondNavigationController setTabBarItem:[[UITabBarItem alloc] initWithTitle:@"List" image:[UIImage imageNamed:@"List.png"] tag:2]];

[viewControllers addObject:secondNavigationController];

UITabBarController *tabBarController = [[UITabBarController alloc] init];

[tabBarController setViewControllers:viewControllers];

[[self window] setRootViewController:tabBarController];

这很好。现在我有一个额外的导航需求,firstViewController 可能会从 secondViewController 中调用,并将数据传递给它。

我发现将数据传递给标签栏访问的同一个 firstViewController 实例的唯一方法如下(在 secondViewController 代码中):

firstViewController = [[[[[self tabBarController] viewControllers] objectAtIndex:0] viewControllers] objectAtIndex:0];

这很好用,但我觉得它很乱,尤其是当我决定更改标签栏控制器中视图的顺序时。

我也探索过标记方式,但似乎对代码没有太大的改进。

还有其他更清洁的方法吗?

【问题讨论】:

    标签: iphone uiviewcontroller uitabbarcontroller uitableview uitabbaritem


    【解决方案1】:

    我不能声称知道您通过将数据从一个视图控制器发送到另一个视图控制器来尝试完成什么,但如果发送数据是您的唯一目的,那么我会推荐 Singleton Pattern。或者我会推荐NSNotificationCenter。单例可以保存可以从任何地方检索的应用程序范围的数据。您甚至可以(尽管它违反最佳实践)在单例类中保存对您的视图控制器的引用。我还大量使用通知来传递数据。只需发布通知并让其他班级收听即可。

    例如,在 viewDidLoad 中的 firstViewController 中,您可以这样做:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(theMethodToCall:) name:@"myNotificationName" object:nil];
    

    然后在 secondViewController 中,当你想传递数据时,你可以发布这个( 其中“myData”是一个数据对象(如 NSDictionary)):

    [[NSNotificationCenter defaultCenter] postNotificationName:myNotificationName object:nil userInfo: myData];
    

    然后在 firstViewController 这个方法会接收数据。

    -(void)theMethodToCall:(NSNotification *)notif
     {
          NSDictionary *dict = [notification userInfo];
     }
    

    使用此代码,您还可以获得不错的对象引用

    【讨论】:

    • 嗨 Spentak,你当然是对的,我确实已经在使用单例模式将全局数据传递给不同的视图控制器。在这种情况下,我避免了它,因为接收视图控制器基本上是在编辑发送视图控制器中选择的行的数据。这在某种程度上是从我介绍标签栏控制器之前应用程序的方式继承的,但我会探索通知方式,即使它看起来不那么干净。尽管如此,我的问题是了解是否有比我更好的方法来识别不同的标签栏视图控制器实例。
    猜你喜欢
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    相关资源
    最近更新 更多