複数のUITabBarセクション用の1つのViewController
-
06-07-2019 - |
質問
現在、UITabBarとテーブルビューを使用してデータを表示するシンプルなiPhoneアプリケーションを開発しています。タブバーには8つのセクションがあり、各セクションには同じビューが含まれますが、異なるデータソースを使用します。テーブルビューのタイトルも異なりますが、ビューは同じです。
8つの個別のビューコントローラーを最小限の違いで作成する代わりに、各ビューに同じビューコントローラーを使用し、データソースとテーブルのタイトルを設定するオプションを使用したいと思います。それは可能でしょうか、さらに重要なことは、どのようにこれが可能でしょうか?
更新
Ole Begemannが投稿したコードを使用して、ある程度機能しています。しかし、最初の質問には専門用語が混同されていることに気付きました。 UITableViewDataSourceは公式のプロトコルであり、私が達成しようとしていることに対してあまりにも多くのことを行います。テーブルを一度セットアップするためのロジックが必要なだけで、テーブルビューに入力するデータのみが異なります。 " datasource"の意味ビューコントローラーの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に渡すにはどうすればよいですか?
解決
ダニエルが言ったように、必要に応じて同じView Controllerのインスタンスを作成し、これらのインスタンスをTab Bar Controllerのタブに割り当てます。
コードは次のようになります(ここでは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];
他のヒント
もちろん、異なるデータソースの場合と同じように、ビューコントローラーを何度でもインスタンス化できます...各タブに異なるビューコントローラーがある場合と同じ手順に従います...
任意のボタンでUIToolBarを使用し、ボタンのクリックごとにreloadDataを異なるパラメーターで呼び出すことができます。