// // ViewController.m // 07-UITableView // // Created by kaiyi wang on 16/10/31. // Copyright © 2016年 Corwien. All rights reserved. // #import "ViewController.h" @interface ViewController ()<UITableViewDataSource,UITableViewDelegate> @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 1.添加tableView UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped]; // 設置行高 tableView.rowHeight = 50; // 底部放置控件 tableView.tableFooterView = [[UISwitch alloc] init]; // 設置數據源 tableView.dataSource = self; [self.view addSubview:tableView]; // self.tableView.dataSource = self; } #pragma mark - 數據源方法 /** * 一共多少組數據 */ -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 2; } /** * 第section組有多少行 */ -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if(section == 0) { return 3; }else{ return 4; } } /** * 每一行顯示怎樣的內容 */ -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // 1.定義一個標示, static修飾局部變量,能夠保證局部變量只分配一次存儲空間(之初始化一次) static NSString *ID = @"myCell"; // 2.從緩存池中取出cell UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; // 3.若是緩存池中沒有cell,則建立 if(cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID]; } // 設置Cell背景 // UIImageView *bgView = [[UIImageView alloc] init]; // bgView.image = [UIImage imageNamed:@"meizi.jpg"]; // cell.backgroundView = bgView; // cell.accessoryType = UITableViewCellAccessoryCheckmark; if(indexPath.section == 0){ // 第0組(影星) if(indexPath.row == 0) // 第0組的第0行 { cell.textLabel.text = @"Jack Ma"; } else if(indexPath.row == 1) { cell.textLabel.text = @"Jack Chan"; } else if(indexPath.row == 2) { cell.textLabel.text = @"Jet Lee"; } } else // 第1組(商人) { if(indexPath.row == 0) { cell.textLabel.text = @"Pony Ma"; } else if(indexPath.row == 1) { cell.textLabel.text = @"Judy Lee"; } else if(indexPath.row == 2) { cell.textLabel.text = @"Jobs Steve"; } else if(indexPath.row == 3) { cell.textLabel.text = @"Gates Bill"; } } return cell; } /** * 第section組顯示怎樣的頭部xinxi */ -(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { if(section == 0){ return @"演員"; }else{ return @"商人"; } } /** * 第section組顯示怎樣的頭部xinxi */ -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { if(section == 0){ return @"演員"; }else{ return @"商人"; } } /** * 選中行時 */ -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // NSLog(@"---select----%d", indexPath.row); // 0.取消選中這一行(去掉cell默認的藍色背景) // [tableView deselectRowAtIndexPath:indexPath animated:YES]; // 1.取出選中行的Cell對象 UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath]; selectedCell.accessoryType = UITableViewCellAccessoryCheckmark; } @end