代码之家  ›  专栏  ›  技术社区  ›  mensch

一个viewcontroller用于多个uitabar部分

  •  3
  • mensch  · 技术社区  · 15 年前

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

    我想为每个视图使用相同的viewcontroller,并提供设置数据源和表标题的选项,而不是编写8个具有最小差异的单独viewcontroller。这有可能吗?更重要的是,这怎么可能呢?

    更新
    我用ole begemann发布的代码让它在一定程度上工作。然而,我意识到我最初的问题混淆了一些行话。uitableviewdatasource是一个正式的协议,它为我想要完成的工作做了太多的工作。我只需要设置一次表的逻辑,填充表视图的数据是唯一不同的东西。我所说的“数据源”只是一个对象字典,它可以由我的VIEW控制器的UITababVIEW函数使用。

    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 回复  |  直到 15 年前
        1
  •  4
  •   Community CDub    7 年前

    AS 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];
    
        2
  •  1
  •   Daniel    15 年前

    当然,这是可能的,因为你可以像UD一样用不同的数据源来实例化视图控制器……你会遵循同样的过程,就好像你对每个选项卡有不同的视图控制器一样…

        3
  •  0
  •   Morion    15 年前

    你可以使用你想要的任何按钮,并在每一个按钮上用不同的参数调用。