UITableView
のインスタンスを1つだけ保持して、タブバーの選択を使用して、使用するデータソースを決定できます。ストーリーボードのビューコントローラーを設定して、タブバーと単一のテーブルビューを含む実例を示します。
#import "ViewController.h"
@interface ViewController() <UITableViewDataSource, UITabBarDelegate>
@property(weak,nonatomic) IBOutlet UITableView *tableView;
@property(weak,nonatomic) IBOutlet UITabBar *tabBar;
@property(strong,nonatomic) NSArray *model;
@end
私たちのモデルは3つの配列で、タブバーの各タブに1つずつあります。これらの配列はここではハードコードで初期化されていますが、Webサービスから初期化することもできます。
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *dataSource0 = @[ @"A", @"B", @"C" ];
NSArray *dataSource1 = @[ @"1", @"2", @"3"];
NSArray *dataSource2 = @[ @"doh", @"ray", @"me"];
self.model = @[ dataSource0, dataSource1, dataSource2 ];
self.tabBar.selectedItem = self.tabBar.items[0];
}
// the user pressed a tab, reload the table
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
[self.tableView reloadData];
}
// this is an important part: our data for the table is determined by
// which tab is selected, return of the arrays, corresponding to the selection
- (NSArray *)currentDataSource {
UITabBarItem *item = self.tabBar.selectedItem;
NSInteger index = [self.tabBar.items indexOfObject:item];
return self.model[index];
}
// these datasource methods always refer to the currentDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self currentDataSource].count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
NSString *text = [self currentDataSource][indexPath.row];
cell.textLabel.text = text;
return cell;
}
@end
@VladHatkoまあ、同じテーブルビューを使用して2セットのデータそれに – JAL
@Rohit palod複数のtableViewを作成する場合は、複数のメモリがあるとみなし、1つのtableViewを使用して、アイテムを切り替えるときに複数のdataSourceを読み込むことができます。複数のtableViewを使用することは推奨ではありませんが、isHiddenを設定して要件を関連付けることもできます。 – aircraft
TableViewsはUI要素です。 'UITableViewDataSource'を使って、テーブルのデータとカスタマイズを提供します。 2つの画面がtableViewで使用されているデータの外側でまったく同じである場合は、1つの表を使用して、それが使用するデータを操作する必要があります。 – Connor