一个用于多个UITabBar部分的viewcontroller

时间:2009-10-26 16:43:43

标签: iphone objective-c uiviewcontroller

我目前正在开发一个使用UITabBar的简单iPhone应用程序和用于显示数据的表视图。标签栏包含8个部分,每个部分包含相同的视图,但使用不同的数据源,表格视图的标题也不同,但除此之外,视图是相同的。

我想为每个视图使用相同的viewcontroller,使用选项来设置数据源和表标题,而不是编写具有最小差异的8个单独的viewcontroller。这是否可能,更重要的是,这将如何成为可能?

更新
我使用Ole Begemann发布的代码在一定程度上工作。但是,我意识到我最初的问题混淆了一些术语。 UITableViewDataSource是一个官方协议,对我想要完成的事情做了太多。我只需要逻辑来设置一次表,填充表视图的数据是唯一不同的。我所说的“datasource”只是一个对象字典,可以被我的viewcontroller的UITableView函数使用。

NSDictionary *row1 = [[NSDictionary alloc] initWithObjectsAndKeys:@"1", @"Id", 
                    @"The Name", @"Name", 
                    @"Post", @"Type",
                    @"09-09-2009", @"Meta",
                    @"This is the excerpt, @"Excerpt",
                    @"This is the body text", @"Body",
                    @"icon.jpg", @"Icon", 
                    @"image.jpg", @"Image", nil];

NSArray *array = [[NSArray alloc] initWithObjects:row1, nil];

如何将此字典从委托传递给UITableViewController?

3 个答案:

答案 0 :(得分:4)

作为Daniel says,您可以根据需要创建同一个视图控制器的任意数量的实例,然后将这些实例分配给选项卡栏控制器的选项卡。

代码看起来像这样(我这里只创建3个实例):

// Create an array of dictionaries that holds the configuration for the table view controllers.
// Assuming tableXDatasource are existing objects that conform to the UITableViewDataSource protocol.
NSArray *tableControllersConfig = [NSArray arrayWithObjects:
    [NSDictionary dictionaryWithObjectsAndKeys:table1Datasource, @"datasource", @"Table 1", @"title", nil],
    [NSDictionary dictionaryWithObjectsAndKeys:table2Datasource, @"datasource", @"Table 2", @"title", nil],
    [NSDictionary dictionaryWithObjectsAndKeys:table3Datasource, @"datasource", @"Table 3", @"title", nil],
    nil];

// Create the table view controller instances and store them in an array
NSMutableArray *tableControllers = [NSMutableArray array];
for (NSDictionary *configDict in tableControllersConfig) {
    // Assuming MyTableViewController is our custom table view controller class
    MyTableViewController *controller = [[MyTableViewController alloc] initWithNibName:@"MyTableViewController" bundle:nil];
    controller.tableView.delegate = controller;
    controller.tableView.dataSource = [configDict valueForKey:@"datasource"];
    controller.title = [configDict valueForKey:@"title"];
    [tableControllers addObject:controller];
    [controller release];
}

// Assign the array of table view controllers to the tab bar controller
self.tabBarController.viewControllers = [NSArray arrayWithArray:tableControllers];

答案 1 :(得分:1)

当然可能,你可以像使用不同的数据源一样多次实例化视图控制器...你会按照你想要的每个标签的不同视图控制器的相同程序...

答案 2 :(得分:0)

您可以将UIToolBar与您想要的任何按钮一起使用,并在每个按钮上使用不同的参数调用reloadData。