UITableView 是 iOS 中最常見的列表元件。它透過 dataSource 提供資料,透過 delegate 處理互動。以下是一個基礎範例。
items = [NSMutableArray arrayWithObjects:@"AA", @"BB", @"CC", @"DD", @"EE", nil];
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, 320, 400) style:UITableViewStylePlain];
tableView.dataSource = self;
tableView.delegate = self;
[self.view addSubview:tableView];
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return items.count + 1;
}
使用固定 identifier 可以讓 Cell 被重複使用,提升效能。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
if (indexPath.row == items.count) {
cell.textLabel.text = @"載入更多";
} else {
cell.textLabel.text = items[indexPath.row];
}
return cell;
}
若點擊最後一列的載入更多,可以觸發非同步載入。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == items.count) {
[self performSelectorInBackground:@selector(loadMore) withObject:nil];
}
}
- (void)loadMore {
NSArray *more = @[@"11", @"22", @"33"];
[self performSelectorOnMainThread:@selector(appendItems:) withObject:more waitUntilDone:NO];
}
- (void)appendItems:(NSArray *)data {
for (NSUInteger index = 0; index != data.count; index++) {
[items addObject:data[index]];
}
[tableView reloadData];
}
這個範例展示了 UITableView 的基本生命週期:建立資料、回傳列數、配置 Cell、處理點擊,以及透過背景佇列載入更多資料。