本文記錄如何在 iOS 中實現 UITableView 嵌套 UITableView 的效果。整體思路是:在同一個控制器裡定義兩個 tableView,一個作為外層的 rootTable,另一個作為被嵌套的內層 tableView1。當我們同時實現 UITableViewDelegate 和 UITableViewDataSource 代理時,該如何區分事件究竟來自哪個 tableView 呢?
其實很簡單,有兩種常見做法:一是給兩個 tableView 分別設置不同的 tag 值,通過 tag 來判斷;二是直接在代理方法裡判斷 tableView == rootTable,成立時執行外層邏輯,否則執行內層 tableView1 的邏輯。本文採用第二種方式。測試環境為 Xcode 6.1。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
UITableView *rootTable;
UITableView *tableView1;
NSMutableArray *ChildArr;
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
[self initView];
ChildArr = [[NSMutableArray alloc] initWithObjects:@"蘋果", @"栗子", @"香蕉", @"菠蘿", @"桃子", @"荔枝", nil];
self.navigationItem.title = @"TwoTableView";
}
-(void)initView {
rootTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 65, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];
rootTable.delegate = self;
rootTable.dataSource = self;
[self.view addSubview:rootTable];
}
行高設置——外層第一行足夠高,用來容納內層表格:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView == rootTable) {
if (indexPath.row == 0) {
return [ChildArr count] * 44;
} else {
return 70;
}
} else {
return 44;
}
}
分組數與行數:
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (tableView == rootTable) {
return 5;
} else {
return 1;
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == rootTable) {
return 4;
} else {
return [ChildArr count];
}
}
單元格配置——關鍵在於,外層第一行創建並添加內層 tableView,並關閉其滾動:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[UITableViewCell alloc] init];
if (tableView == rootTable) {
if (indexPath.row == 0) {
tableView1 = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, [ChildArr count] * 44)];
tableView1.delegate = self;
tableView1.dataSource = self;
tableView1.scrollEnabled = NO;
[cell.contentView addSubview:tableView1];
} else {
cell.textLabel.text = @"rootTableView";
}
return cell;
} else {
cell.textLabel.text = [ChildArr objectAtIndex:indexPath.row];
cell.backgroundColor = [UIColor yellowColor];
return cell;
}
}
點擊事件同樣需要區分來源:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView == rootTable) {
NSLog(@"rootTableView");
} else {
NSLog(@"蘋果");
}
}
總結一下實現嵌套表格的兩個要點:其一,通過比較 tableView 與外層 rootTable 是否相等(或依賴 tag)來在共享的代理方法中區分事件來源;其二,把內層 tableView 作為子視圖添加到外層某個 cell 的 contentView 上,並記得把內層表格的 scrollEnabled 設為 NO,避免層層滾動帶來的交互混亂。這種思路可以靈活擴展到多層嵌套的場景。