TableView 是一個可滾動的單列多行列表,每一行是一個 UITableViewCell。它提供兩種風格:
typedef NS_ENUM(NSInteger, UITableViewStyle) {
UITableViewStylePlain, // 普通樣式
UITableViewStyleGrouped, // 分組樣式
};

此外它還支援索引欄(像通訊錄右側那排字母),每個索引項對應一個分區的頭部標題:


最簡單的形態是單選列表,可以限制單選或多選(如右圖)。頁眉頁腳也可以按需要自定義。

系統只會保留可見行的 cell,其餘進緩存池等待複用。資料填充透過 UITableViewDataSource 的 cellForRowAtIndexPath 完成。
Cell 有四種內建樣式:
UITableViewCellStyleDefault, // 一個 imageView + 一個 textLabel UITableViewCellStyleValue1, // imageView + textLabel + detailLabel(detail 在右,藍色右對齊) UITableViewCellStyleValue2, // textLabel(藍色右對齊)+ detailLabel(緊鄰其右,黑色左對齊) UITableViewCellStyleSubtitle // imageView + textLabel + detailLabel(detail 在下方,字體較小)
本文以純代碼方式建立(不含 storyboard 拖拽)。


第一步,建立 Single View Application,命名為 tableView。
第二步,建立一個繼承自 UITableView 的類,把列表相關實現都收攏在裡面。分離出來的好處很實際:當 ViewController 代碼量膨脹,或同一個列表要在多處使用時,複用成本會低很多。命名為 general_table_view。
第三步,在頭文件中聲明屬性:
@interface general_table_view : UITableView // tableView 的坐標 @property (nonatomic, assign) CGRect tableViewFrame; // 各行 textLabel 的值 @property (nonatomic, copy) NSMutableArray *textLabel_MArray; // 各行 imageView 的圖片 @property (nonatomic, copy) NSMutableArray *images_MArray; // 各行 detailLabel 的值 @property (nonatomic, copy) NSMutableArray *subtitle_MArray; @end
在 .m 的匿名類別中聲明代理,並在初始化時把自己設為代理:
@interface general_table_view () <UITableViewDataSource, UITableViewDelegate> @end
// 設置代理 self.delegate = self; self.dataSource = self;
// 通過 setter 同步 frame
-(void)setTableViewFrame:(CGRect)tableViewFrame
{
self.frame = tableViewFrame;
}
接著實現兩個必須完成的數據源方法:
// 每個分區的行數,可依 section 分別返回
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_textLabel_MArray count];
}
// 每行 cell 的內容,這裡體現了複用機制
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 標識符是複用機制的關鍵,系統靠它匹配可重用的 cell
static NSString *cellIdentifier = @"cellIdentifier";
// 先從緩存隊列取
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
// 取不到才新建
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier];
cell.accessoryType = UITableViewCellAccessoryNone;
}
cell.textLabel.text = [_textLabel_MArray objectAtIndex:indexPath.row];
return cell;
}
其他輔助方法按需添加:
// 分區數量,預設 1
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
// 頁眉標題
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return @"頁眉";
}
// 頁腳標題
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
return @"頁腳";
}
最後在需要的 ViewController 中放進列表:
#import "general_table_view.h"
@interface ViewController ()
{
general_table_view *table;
}
@end
table = [[general_table_view alloc] initWithFrame:CGRectMake(0, 20, 320, self.view.frame.size.height - 20)
style:UITableViewStylePlain];
table.textLabel_MArray = [[NSMutableArray alloc] initWithObjects:
@"南京市", @"南通市", @"淮安市", @"鎮江市", @"揚州市", @"常州市", nil];
[self.view addSubview:table];
把 style 換成 UITableViewStyleGrouped,就是分組樣式的效果。
在 addSubview 之前先準備圖片數組,並在 cellForRow 中賦值:
NSMutableArray *images = [NSMutableArray array];
for (NSInteger index = 0; index < [table.textLabel_MArray count]; index++) {
UIImage *image = [UIImage imageNamed:@"2"];
[images addObject:image];
}
table.images_MArray = [[NSMutableArray alloc] initWithArray:images];
// 設置每一行的圖片 cell.imageView.image = [_images_MArray objectAtIndex:indexPath.row];
在初始化 cell 時換掉 style,並補上 detailTextLabel:
NSMutableArray *subtitle = [NSMutableArray array];
for (NSInteger index = 0; index < [table.textLabel_MArray count]; index++) {
UIImage *image = [UIImage imageNamed:@"2"];
NSString *detail = [NSString stringWithFormat:@"detail text %d", index + 1];
[images addObject:image];
[subtitle addObject:detail];
}
table.subtitle_MArray = [[NSMutableArray alloc] initWithArray:subtitle];
// 設置小標題 cell.detailTextLabel.text = [_subtitle_MArray objectAtIndex:indexPath.row];




-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"您點擊了第%d分區第%d行", indexPath.section, indexPath.row);
// 若不想保持高亮,取消選中狀態
// [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
先允許編輯:
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
左滑即出現刪除按鈕:

按鈕標題默認是 "delete",可以改:
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @"刪除";
}
點擊確認後的處理——記得同時更新資料源和界面,兩者必須一致,否則後續滾動會崩潰:
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.dataArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
把插入與刪除都做成按鈕觸發,點擊後進入編輯模式:


NSArray *leftBarButtons = [NSArray arrayWithObjects:self.addButton, self.deleteBarButtonItem, nil]; self.navigationItem.leftBarButtonItems = leftBarButtons;
// 用一個變量記錄當前期望的編輯樣式 UITableViewCellEditingStyle selectEditingStyle;
// 更新導航欄按鈕
-(void) updateBarButtons
{
if (self.tableView.editing == YES) {
self.navigationItem.rightBarButtonItem = self.doneBarButtonItem;
}
}
// 點擊添加
- (IBAction)addButtonClicked:(id)sender {
selectEditingStyle = UITableViewCellEditingStyleInsert;
[self.tableView setEditing:YES animated:YES];
[self updateBarButtons];
}
// 點擊刪除
- (IBAction)deleteButtonClicked:(id)sender {
selectEditingStyle = UITableViewCellEditingStyleDelete;
[self.tableView setEditing:YES animated:YES];
[self updateBarButtons];
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
// 回傳當前的編輯樣式
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return selectEditingStyle;
}
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.dataArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
[self.dataArray insertObject:@"new iPhone" atIndex:indexPath.row];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
// 點擊完成
- (IBAction)doneButtonClicked:(id)sender {
[self.tableView setEditing:NO animated:YES];
[self updateBarButtons];
}

// 是否支持移動
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
// 移動時同步調整資料源順序
- (void)tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toIndexPath:(NSIndexPath *)destinationIndexPath
{
id object = [self.dataArray objectAtIndex:sourceIndexPath.row];
[self.dataArray removeObjectAtIndex:sourceIndexPath.row];
[self.dataArray insertObject:object atIndex:destinationIndexPath.row];
}
注意原示例中把參數名寫成了 fromIndexPath,實際簽名的參數是 sourceIndexPath,照抄會編譯不通過。


self.navigationItem.rightBarButtonItem = self.editBarButtonItem;
目標是:點編輯後右上角變「取消」、左上角變「批量刪除」,且按鈕標題要隨選中數量變化。因此 updateBarButtons 需要擴充:
-(void) updateBarButtons
{
// 多選模式
if (self.tableView.allowsSelectionDuringEditing == YES) {
[self updateDeleteButtonTitle];
self.navigationItem.leftBarButtonItems = nil;
self.navigationItem.leftBarButtonItem = self.multiDeleteBarButton;
self.navigationItem.rightBarButtonItem = self.cancelBarButtonItem;
return;
}
if (self.tableView.editing == YES) {
self.navigationItem.rightBarButtonItem = self.doneBarButtonItem;
}
else {
NSArray *leftBarButtons = [NSArray arrayWithObjects:self.addButton, self.deleteBarButtonItem, nil];
self.navigationItem.leftBarButtonItems = leftBarButtons;
self.navigationItem.rightBarButtonItem = self.editBarButtonItem;
}
}
// 依選中數量動態改標題
-(void)updateDeleteButtonTitle
{
NSArray *selectedRows = [self.tableView indexPathsForSelectedRows];
BOOL allItemsAreSelected = selectedRows.count == self.dataArray.count;
BOOL noItemsAreSelected = selectedRows.count == 0;
if (allItemsAreSelected || noItemsAreSelected) {
self.multiDeleteBarButton.title = @"刪除全部";
}
else {
self.multiDeleteBarButton.title = [NSString stringWithFormat:@"刪除 (%d)", selectedRows.count];
}
}
在選中與取消選中的回調裡都要呼叫一次標題更新:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self updateDeleteButtonTitle];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self updateDeleteButtonTitle];
}
// 進入多選編輯
- (IBAction)editButtonClicked:(id)sender {
self.tableView.allowsMultipleSelectionDuringEditing = YES;
[self.tableView setEditing:YES animated:YES];
[self updateBarButtons];
}
// 執行批量刪除
- (IBAction)multiDeleteClicked:(id)sender {
NSArray *selectedRows = [self.tableView indexPathsForSelectedRows];
BOOL deleteSpecificRows = selectedRows.count > 0;
if (deleteSpecificRows) {
// 把選中行的索引收集起來批量刪
NSMutableIndexSet *indicesOfItemsToDelete = [NSMutableIndexSet new];
for (NSIndexPath *selectionIndex in selectedRows) {
[indicesOfItemsToDelete addIndex:selectionIndex.row];
}
[self.dataArray removeObjectsAtIndexes:indicesOfItemsToDelete];
[self.tableView deleteRowsAtIndexPaths:selectedRows
withRowAnimation:UITableViewRowAnimationAutomatic];
}
else {
// 一條都沒選,視為刪除全部
[self.dataArray removeAllObjects];
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0]
withRowAnimation:UITableViewRowAnimationAutomatic];
}
// 收尾:退出編輯與多選狀態
[self.tableView setEditing:NO animated:YES];
self.tableView.allowsMultipleSelectionDuringEditing = NO;
[self updateBarButtons];
}
最後強調一個貫穿全篇的原則:所有增刪改的界面動畫,都必須搭配資料源的同步變更,而且批量操作時要用 performBatchUpdates: 把多次改動包成一次事務,否則容易出現動畫錯亂甚至內部索引越界崩潰。