使用故事板的app delegate参考视图

时间:2012-02-25 23:08:54

标签: iphone objective-c ios xcode ios5

我正在尝试使用故事板创建一个UITableView,但我得出的结论可能很简单,但我不知道如何解决它。 首先让我指出,我知道故事板的一个局限是你必须深入了解故事板才能找到有关你所拥有的视图的信息并将其链接到应用代表。 我已经创建了我的可变数组和我将在app delegate中的表中使用的信息,现在我想将UITableView引用到app delegate。层次结构就像那样

  1. 首先我有根视图,一旦你点击一个按钮,它会将你重定向到第二个视图
  2. 在第二个视图中有另一个按钮,按下它后会将您重定向到UINavigationController
  3. UINavigationController包含UITableView。
  4. 因此,您可以看到导航控件和UITableView之前有两个视图。

    以下是我尝试使用的代码,但它不起作用

    UIViewController *viewController = (UIViewController *)self.window.rootviewController;
    
    // The next line refers to the second view but does not work at all
    UIViewController *secondView = [[UIViewController viewController] objectAtIndex:1];
    
    //Then the following line is to redirect from the second view to the navigation controller
    UINavigationController *navigationController =[[secondView viewController] objectAtIndex:0];
    
    //Then is the table view
    BuildingsViewController *buildingsViewController = [[navigationController viewControllers] objectAtIndex:0];
    

    上述代码不起作用。谁能帮帮我吗? 非常感谢

1 个答案:

答案 0 :(得分:2)

如果此代码在应用程序委托中,则有多种原因导致它可能无效。首先,您似乎将View,ViewControllers和Navigation控制器与您尝试的操作混合在一起。其次,在您尝试执行此操作时无法保证所有视图/视图控件尚未创建或以最终构建视图控制器呈现时的方式连接。

您可以尝试使用的是您的BuildingsViewController(您说是您的表视图控制器),您可以使用

获取App Delegate的句柄
MyAppDelegate *myAppDelegate = (MyAppDelegate *)[UIApplication sharedApplication].delegate

一旦掌握了委托,您就可以在BuildingsViewController中引用您在其上创建的可变数组结构等。

e.g。在'numberOfRowsInSection'方法中:

MyAppDelegate *myAppDelegate = (MyAppDelegate *)[UIApplication sharedApplication].delegate
NSMutableArray *myBuildings = myAppDelegate.buildingArray;
return [myBuildings count];

或者在cellForRowAtIndexPath方法中:

// something like this but using your names for app delegate, building array and the accessor for the building name
MyAppDelegate *myAppDelegate = (MyAppDelegate *)[UIApplication sharedApplication].delegate
NSMutableArray *myBuildings = myAppDelegate.buildingArray;

cell.textLabel.text = [myBuildings objectAtIndex indexPath.row].theBuildingName;
相关问题