iOS中表格(UITableView)嵌套表格的簡單實現
首先說一下思路:我們在一個控制器裡面定義2個tableview,一個作為被嵌套的rootTable,一個作為嵌套的表格tableView1,那我們要實現UITableViewDelegate,UITableViewDataSource,的代理的時候,該怎麼區分呢?其實很簡單,有兩種方法,一個是給定義的2個tableview設置tag值,另一個是直接寫出來tableView
== rootTable時實現他得代理,否則就實現tableView1的代理方法。
測試環境 Xcode6.1
Demo的下載地址:
下面是實現的代碼:
ViewController.h #import@interface ViewController : UIViewController { UITableView * rootTable; UITableView * tableView1; NSMutableArray * ChildArr; //NSMutableArray * ChildArr1; //NSMutableArray * ChildArr2; } @end ViewController.m #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [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]; } } -(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(@"蘋果"); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end