UITableView 是我們日常開發中用來展示列表數據的核心元件,作用類似於 Android 的 ListView。相比 Android,UITableView 的實現要簡單許多:只要讓控制器遵循 UITableViewDataSource 和 UITableViewDelegate 兩個協議,再按需要實現對應的方法即可。
UITableView 內建了兩種默認樣式:Plain(平鋪)和 Grouped(分組)。Plain 樣式在你自己提供額外定制之前幾乎不做任何裝飾,它主要負責為你渲染 header 與 footer;Grouped 則是 UIKit 提供的分組外觀。如果有特殊需求,還可以自定義分組樣式。
這個 Demo 的頁面比較簡單,就是一個 UITableView。頭文件中無需額外聲明,只需讓類遵循兩個協議:
@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> @end
我們聲明三個集合,分別用於存放分組標題、電影列表和電視劇列表:
@interface ViewController () {
NSArray *channelArr;
NSMutableArray *filmArr;
NSMutableArray *tvArr;
}
@end
在 viewDidLoad 中完成數據初始化:
- (void)viewDidLoad {
[super viewDidLoad];
channelArr = [[NSArray alloc] initWithObjects:@"電影", @"電視劇", nil];
filmArr = [[NSMutableArray alloc] initWithObjects:@"智取威虎山", @"一步之遙", @"匆匆那年", @"北京愛情故事", nil];
tvArr = [[NSMutableArray alloc] initWithObjects:@"何以笙簫默", @"鋒刃", @"陸小鳳與花滿樓", @"武媚娘傳奇", nil];
}
設置分組數量:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [channelArr count];
}
設置每個分組的標題:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [channelArr objectAtIndex:section];
}
設置每個分組下的行數:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSInteger count = 0;
switch (section) {
case 0:
count = [filmArr count];
break;
case 1:
count = [tvArr count];
break;
}
return count;
}
設置每一行的具體內容:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
switch (indexPath.section) {
case 0:
[cell.textLabel setText:[filmArr objectAtIndex:indexPath.row]];
break;
case 1:
[cell.textLabel setText:[tvArr objectAtIndex:indexPath.row]];
break;
}
return cell;
}
設置分組標題與底部的高度:
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return 0;
}
為每一行添加點擊響應,並用彈窗展示當前選中的位置:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *content;
switch (indexPath.section) {
case 0:
content = [NSString stringWithFormat:@"%@-%@", channelArr[0], [filmArr objectAtIndex:indexPath.row]];
break;
case 1:
content = [NSString stringWithFormat:@"%@-%@", channelArr[1], [tvArr objectAtIndex:indexPath.row]];
break;
}
UIAlertView *alterView = [[UIAlertView alloc] initWithTitle:@"當前位置:" message:content delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
[alterView show];
}
以上就是 UITableView 最基礎也最常用的幾個方法。掌握它們之後,你就能快速搭建出一個功能完整的分組列表頁面。在實際項目中,通常還會配合重用標識(reuseIdentifier)來提升性能,並通過自定義 Cell 實現更豐富的界面效果。