您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發系列:UITableView 全面解析

編輯:iOS 開發綜合

前言

在 iOS 開發中,UITableView 可以說是使用最廣泛的控件。我們日常使用的軟體裡隨處可見它的身影,無論是微信、QQ 還是新浪微博,基本上到處都是 UITableView。它之所以被廣泛採用,自然離不開其強大的功能。本文將針對 UITableView 重點展開,主要內容包括:基本介紹、資料來源與代理、效能優化、UITableViewCell 常用操作,以及 UITableViewController 與 MVC 模式。

一、基本介紹

UITableView 有兩種風格:UITableViewStylePlain 與 UITableViewStyleGrouped。兩者操作起來並無本質差異,只是後者按分組樣式顯示,前者則按普通樣式顯示。

1. 分組樣式

2. 不分組樣式

可以發現,UITableView 中只有「行」的概念而沒有「列」,因為在行動裝置上顯示多列並不利於操作。表格中的每一行都是一個 UITableViewCell,為了呈現更多資訊,iOS 已在其內部預設了多個子控件供開發者使用。查看 UITableViewCell 的宣告檔會發現,內部有一個 UIView(contentView,作為其他元素的父控件)、兩個 UILabel(textLabel、detailTextLabel)與一個 UIImageView(imageView),分別用於容器、顯示內容、詳情與圖片。使用效果類似微信、QQ 的資訊列表:

這些子控件並非一定要全部使用,可透過 UITableViewCellStyle 設定,每個列舉值的意思已在程式碼註解中說明:

 typedef NS_ENUM(NSInteger, UITableViewCellStyle) { UITableViewCellStyleDefault, // 左側顯示 textLabel(不顯示 detailTextLabel),imageView 可選 UITableViewCellStyleValue1, // 左側顯示 textLabel、右側顯示 detailTextLabel(預設藍色),imageView 可選 UITableViewCellStyleValue2, // 左側依次顯示 textLabel(預設藍色)與 detailTextLabel,imageView 可選 UITableViewCellStyleSubtitle // 左上方顯示 textLabel,左下方顯示 detailTextLabel(預設灰色),imageView 可選 };

二、資料來源

由於 iOS 遵循 MVC 模式設計,許多操作都透過代理與外界溝通;但對於資料來源控件,除了代理還有一個 dataSource 屬性,用它與外界進行資料互動。為 UITableView 設定好 dataSource 後,需要實作 UITableViewDataSource 協議,其中定義了多種資料操作方法。下面以建立一個簡單的通訊錄管理為例進行示範。

首先建立聯絡人模型 KCContact:

 // KCContact.h #import  @interface KCContact : NSObject @property (nonatomic, copy) NSString *firstName; // 姓 @property (nonatomic, copy) NSString *lastName; // 名 @property (nonatomic, copy) NSString *phoneNumber; // 手機號碼 -(KCContact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber; -(NSString *)getName; +(KCContact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber; @end
 // KCContact.m #import "KCContact.h" @implementation KCContact -(KCContact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber{ if(self=[super init]){ self.firstName=firstName; self.lastName=lastName; self.phoneNumber=phoneNumber; } return self; } -(NSString *)getName{ return [NSString stringWithFormat:@"%@ %@",_lastName,_firstName]; } +(KCContact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber{ KCContact *contact1=[[KCContact alloc]initWithFirstName:firstName andLastName:lastName andPhoneNumber:phoneNumber]; return contact1; } @end

為了示範分組顯示,我們再把一組資料抽象成模型 KCContactGroup:

 // KCContactGroup.h #import "KCContact.h" @interface KCContactGroup : NSObject @property (nonatomic, copy) NSString *name; // 組名 @property (nonatomic, copy) NSString *detail; // 分組描述 @property (nonatomic, strong) NSMutableArray *contacts; // 聯絡人 -(KCContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts; +(KCContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts; @end
 // KCContactGroup.m #import "KCContactGroup.h" @implementation KCContactGroup -(KCContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts{ if (self=[super init]) { self.name=name; self.detail=detail; self.contacts=contacts; } return self; } +(KCContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts{ KCContactGroup *group1=[[KCContactGroup alloc]initWithName:name andDetail:detail andContacts:contacts]; return group1; } @end

接著在 viewDidLoad 中建立一些模擬資料,並實作資料來源協議方法:

 // KCMainViewController.m #import "KCMainViewController.h" #import "KCContact.h" #import "KCContactGroup.h" @interface KCMainViewController (){ UITableView *_tableView; NSMutableArray *_contacts; // 聯絡人模型 } @end @implementation KCMainViewController - (void)viewDidLoad { [super viewDidLoad]; [self initData]; _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped]; _tableView.dataSource=self; [self.view addSubview:_tableView]; } #pragma mark 資料來源方法 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return _contacts.count; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ KCContactGroup *group1=_contacts[section]; return group1.contacts.count; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ // NSIndexPath 是一個物件,記錄了組與行資訊 KCContactGroup *group=_contacts[indexPath.section]; KCContact *contact=group.contacts[indexPath.row]; UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil]; cell.textLabel.text=[contact getName]; cell.detailTextLabel.text=contact.phoneNumber; return cell; } -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ KCContactGroup *group=_contacts[section]; return group.name; } -(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{ KCContactGroup *group=_contacts[section]; return group.detail; } @end

運行後即可看到分組的通訊錄效果:

使用 iPhone 通訊錄時會發現右側能按字母檢索,相當方便。其實這個功能用 UITableView 實作很簡單,只要實作資料來源協議的 sectionIndexTitlesForTableView: 方法,建立一個分組標題陣列即可。需注意,UITableView 是按陣列元素的索引與每組資料的索引順序來定位,而非按內容查找。

 -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{ NSMutableArray *indexs=[[NSMutableArray alloc]init]; for(KCContactGroup *group in _contacts){ [indexs addObject:group.name]; } return indexs; }

效果如下:

值得留意的是幾個重點方法的執行順序(見下圖)。此外,產生單元格的方法並非一次全部呼叫,而是只產生當前顯示在畫面上的單元格,當使用者滾動時才會再產生其他單元格。

注意:隨著應用越來越複雜,經常需要除錯。iOS 預設情況下無法定位到出錯的程式碼行,可透過 Show the Breakpoint navigator → Add Exception breakpoint 的設定,讓程式在出錯時自動定位到問題行。

三、代理

上面我們完成了通訊錄的簡單實現,但會發現單元格高度、分組標題高度與尾部說明高度都需要調整,此時就要用到代理方法。UITableView 的代理方法眾多,例如監聽單元格的顯示週期、監聽選擇與編輯操作、設定是否高亮、設定行高等。

1. 設定行高

 -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{ if(section==0){ return 50; } return 40; } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ return 45; // 每行高度可以不同 } -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{ return 40; }

2. 監聽點擊

在 iOS 中點擊某個聯絡人即可呼叫,這時需要監聽點擊操作。這裡示範修改人員資訊的操作。

 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ _selectedIndexPath=indexPath; KCContactGroup *group=_contacts[indexPath.section]; KCContact *contact=group.contacts[indexPath.row]; // 建立彈出視窗 UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"System Info" message:[contact getName] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; alert.alertViewStyle=UIAlertViewStylePlainTextInput; UITextField *textField=[alert textFieldAtIndex:0]; textField.text=contact.phoneNumber; [alert show]; } // 視窗代理方法:使用者保存資料 -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ if (buttonIndex==1) { UITextField *textField=[alertView textFieldAtIndex:0]; // 修改模型資料 KCContactGroup *group=_contacts[_selectedIndexPath.section]; KCContact *contact=group.contacts[_selectedIndexPath.row]; contact.phoneNumber=textField.text; // 局部刷新表格(比 reloadData 更可取) NSArray *indexPaths=@[_selectedIndexPath]; [_tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft]; } }

在上面的程式碼中,我們透過修改模型來改變 UI 顯示,這是典型的 MVC 應用。畫面刷新使用了 UITableView 的 reloadData 方法,它會重新呼叫資料來源方法(計算分組、行數、產生單元格等),刷新整個表格。但這種做法在實務中並不可取——我們不可能因為改了一筆資料就刷新整個表格,此時應採用局部刷新:

 -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ if (buttonIndex==1) { UITextField *textField=[alertView textFieldAtIndex:0]; KCContactGroup *group=_contacts[_selectedIndexPath.section]; KCContact *contact=group.contacts[_selectedIndexPath.row]; contact.phoneNumber=textField.text; NSArray *indexPaths=@[_selectedIndexPath];// 需要局部刷新的單元格 [_tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft]; } }

四、效能優化

如前所述,UITableView 的單元格是在顯示到使用者可視區域後才建立的。當使用者往下滾動會持續建立新單元格,向上滾動回到看過的內容時又會重新建立。如此一来,即使內容不多,反覆上下滾動也會讓記憶體瞬間飆升,更何況很多列表(如微博)幾乎沒有底線。

同樣地,在 UITableView 中也可以採用類似 UIScrollView 的優化思路:把當前未顯示的 Cell 重新定位到即將顯示的位置,再更新其內容,藉此重用已建立過、不再顯示的 Cell。所幸 UITableView 已為我們實作了這套機制——內部有一個快取池。初始化時透過 initWithStyle:reuseIdentifier: 指定一個可重用標識,就能把 Cell 放進快取池;使用時再用該標識從池中取出對應 Cell 並更新內容即可。

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ KCContactGroup *group=_contacts[indexPath.section]; KCContact *contact=group.contacts[indexPath.row]; // 此方法呼叫頻繁,標識宣告為靜態變數有利於效能 static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1"; // 先從快取池取 UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; // 若池中沒有則重新建立並放入池中 if(!cell){ cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier]; } cell.textLabel.text=[contact getName]; cell.detailTextLabel.text=contact.phoneNumber; return cell; }

程式中已印出 Cell 的位址,若運行測試並上下滾動,會發現滾動時「建立」的 Cell 位址其實是初始化時已建立的那些。這裡再次強調兩點:

cellForRowAtIndexPath: 方法呼叫非常頻繁,無論初始化、滾動還是刷新都會觸發,因此其中的操作務必注意效能;可重用標識可以有多個,若表格中有多種結構不同的 Cell,可用不同標識分別快取與重用。

五、UITableViewCell

1. 系統自帶的 UITableViewCell

UITableViewCell 是建構 UITableView 的基礎,內部有一個 UIView 作為容器,上面有一個 UIImageView 與兩個 UILabel,透過 UITableViewCellStyle 屬性可控制其樣式,結構如下:

我們常看到某些 UITableViewCell 右側可顯示不同圖標,iOS 稱之為「訪問器」(Accessory),點擊可觸發不同事件:

UITableViewCellAccessoryType

要設定這些圖標,只需設定 UITableViewCell 的 accessoryType 屬性,這是一個列舉類型:

 typedef NS_ENUM(NSInteger, UITableViewCellAccessoryType) { UITableViewCellAccessoryNone, // 不顯示任何圖標 UITableViewCellAccessoryDisclosureIndicator, // 跳轉指示圖標 UITableViewCellAccessoryDetailDisclosureButton, // 內容詳情圖標與跳轉指示圖標 UITableViewCellAccessoryCheckmark, // 勾選圖標 UITableViewCellAccessoryDetailButton // 內容詳情圖標(iOS 7 之後) };

例如在「最近通話」中通常設為詳情圖標,點擊可查看聯絡人詳情:

那麼如何顯示自定義的訪問器(如 iOS 設定中的 UISwitch)呢?其實只要設定 UITableViewCell 的 accessoryView 即可,它支援任何 UIView 控件。以下示範在通訊錄每組第一行放一個 UISwitch,切換時輸出對應資訊:

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ KCContactGroup *group=_contacts[indexPath.section]; KCContact *contact=group.contacts[indexPath.row]; static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1"; static NSString *cellIdentifierForFirstRow=@"UITableViewCellIdentifierKeyWithSwitch"; UITableViewCell *cell; if (indexPath.row==0) { cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifierForFirstRow]; }else{ cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; } if(!cell){ if (indexPath.row==0) { cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifierForFirstRow]; UISwitch *sw=[[UISwitch alloc]init]; [sw addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventValueChanged]; cell.accessoryView=sw; }else{ cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier]; cell.accessoryType=UITableViewCellAccessoryDetailButton; } } if(indexPath.row==0){ ((UISwitch *)cell.accessoryView).tag=indexPath.section; } cell.textLabel.text=[contact getName]; cell.detailTextLabel.text=contact.phoneNumber; return cell; } -(void)switchValueChange:(UISwitch *)sw{ NSLog(@"section:%i, switch:%i", sw.tag, sw.on); }

最終運行效果如下:

注意:

-此時需要兩種 Cell 樣式,為兼顧效能需在快取池中快取兩種 Cell。

-UISwitch 繼承自 UIControl 而非 UIView,因此使用 addTarget 而非代理來綁定事件,並具備「是否可用」「是否高亮」「是否選中」等屬性。

-由於 Cell 會被重用,若某 Cell 的 UISwitch 設為 on,其他重用它的 Cell 也可能呈現 on,解決之道是在模型中記錄狀態,並在產生 Cell 時設定當前狀態。

2. 自定義 UITableViewCell

系統自帶的 UITableViewCell 雖已相當強大,但仍有無法滿足需求的時候,例如新浪微博的 Cell 就沒那麼簡單。下面我們實作一個簡化版本,界面原型如下:

對控件進行拆分後可見,這個界面由 2 個 UIImageView 與 4 個 UILabel 組成,效果類似新浪微博的內容界面,但經過精簡。

實務中資料不會手動建立,這裡我們把微博資料存到 plist 檔,再從中讀取並建立模型物件。假設 plist 內容如下:

接著定義 KCStatusTableViewCell。自定義 Cell 一般分兩步:先初始化控件,再設定資料並重新計算控件 frame。原因是自定義 Cell 的高度往往需隨內容變化,而 Cell 內部無法控制自身高度,因此通常會定義一個高度屬性,供 UITableView 的代理方法設定每行高度使用。

1. 先看微博模型 KCStatus,其核心方法是依 plist 字典內容建立微博物件:

 // KCStatus.h @interface KCStatus : NSObject @property (nonatomic, assign) long long Id; // 微博 id @property (nonatomic, copy) NSString *profileImageUrl; // 頭像 @property (nonatomic, copy) NSString *userName; // 發送用戶 @property (nonatomic, copy) NSString *mbtype; // 會員類型 @property (nonatomic, copy) NSString *createdAt; // 創建時間 @property (nonatomic, copy) NSString *source; // 設備來源 @property (nonatomic, copy) NSString *text; // 微博內容 -(KCStatus *)initWithDictionary:(NSDictionary *)dic; +(KCStatus *)statusWithDictionary:(NSDictionary *)dic; @end
 // KCStatus.m #import "KCStatus.h" @implementation KCStatus -(KCStatus *)initWithDictionary:(NSDictionary *)dic{ if(self=[super init]){ self.Id=[dic[@"Id"] longLongValue]; self.profileImageUrl=dic[@"profileImageUrl"]; self.userName=dic[@"userName"]; self.mbtype=dic[@"mbtype"]; self.createdAt=dic[@"createdAt"]; self.source=dic[@"source"]; self.text=dic[@"text"]; } return self; } +(KCStatus *)statusWithDictionary:(NSDictionary *)dic{ KCStatus *status=[[KCStatus alloc]initWithDictionary:dic]; return status; } -(NSString *)source{ return [NSString stringWithFormat:@"來自 %@",_source]; } @end

2. 接著看自定義的 Cell。它分兩步:先在 initSubView 中初始化各控件並設定格式(字體、顏色等);再在 setStatus: 中進行布局(大小、位置)。幾點重點提示:

 // KCStatusTableViewCell.h @class KCStatus; @interface KCStatusTableViewCell : UITableViewCell @property (nonatomic, strong) KCStatus *status; // 微博物件 @property (assign, nonatomic) CGFloat height; // 單元格高度 @end
 // KCStatusTableViewCell.m #import "KCStatusTableViewCell.h" #import "KCStatus.h" @interface KCStatusTableViewCell(){ UIImageView *_avatar; UIImageView *_mbType; UILabel *_userName; UILabel *_createAt; UILabel *_source; UILabel *_text; } @end @implementation KCStatusTableViewCell - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { [self initSubView]; } return self; } -(void)initSubView{ _avatar=[[UIImageView alloc]init]; [self.contentView addSubview:_avatar]; _userName=[[UILabel alloc]init]; [self.contentView addSubview:_userName]; _mbType=[[UIImageView alloc]init]; [self.contentView addSubview:_mbType]; _createAt=[[UILabel alloc]init]; [self.contentView addSubview:_createAt]; _source=[[UILabel alloc]init]; [self.contentView addSubview:_source]; _text=[[UILabel alloc]init]; _text.numberOfLines=0; [self.contentView addSubview:_text]; } -(void)setStatus:(KCStatus *)status{ // 依各控件內容計算大小與位置後設定 frame ... // 多行文本用 boundingRectWithSize 計算 _height=CGRectGetMaxY(_text.frame)+kStatusTableViewCellControlSpacing; } // 重寫選擇事件,取消選中 -(void)setSelected:(BOOL)selected animated:(BOOL)animated{ } @end

這裡有幾點需重點提示:

-單行文本用 sizeWithAttributes: 取得寬高;多行文本用 boundingRectWithSize:options:attributes:context: 取得寬高,並在事前將 text 控件的 numberOfLines 設為 0。

-通常在自定義 Cell 中設定一個高度屬性供外界呼叫,因為 Cell 內部設定高度是無效的,UITableViewCell 初始化時會重新設定高度。

3. 最後看自定義 Cell 的使用:

 // KCStatusViewController.m @interface KCStatusCellViewController (){ UITableView *_tableView; NSMutableArray *_status; NSMutableArray *_statusCells; // 存儲 cell,用於計算高度 } @end @implementation KCStatusCellViewController -(void)initData{ NSString *path=[[NSBundle mainBundle] pathForResource:@"StatusInfo" ofType:@"plist"]; NSArray *array=[NSArray arrayWithContentsOfFile:path]; _status=[[NSMutableArray alloc]init]; _statusCells=[[NSMutableArray alloc]init]; [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [_status addObject:[KCStatus statusWithDictionary:obj]]; KCStatusTableViewCell *cell=[[KCStatusTableViewCell alloc]init]; [_statusCells addObject:cell]; }]; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1"; KCStatusTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if(!cell){ cell=[[KCStatusTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } cell.status=_status[indexPath.row]; return cell; } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ // Cell 高度需重新設定 KCStatusTableViewCell *cell=_statusCells[indexPath.row]; cell.status=_status[indexPath.row]; return cell.height; } @end

這個類別需重點強調:Cell 的高度必須重新設定(前面提過,內部設定無效)。做法是先建立對應 Cell,再在 heightForRowAtIndexPath: 中設定微博資料、計算高度並通知 UITableView。

最後看運行效果:

六、常用操作

UITableView 與 UITableViewCell 提供了強大的操作能力,本節重點討論刪除、新增、排序等操作,仍以之前的通訊錄為基礎。先為視圖控制器加上一個工具列,左側放刪除按鈕、右側放新增按鈕:

 -(void)addToolbar{ CGRect frame=self.view.frame; _toolbar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, kContactToolbarHeight)]; [self.view addSubview:_toolbar]; UIBarButtonItem *removeButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(remove)]; UIBarButtonItem *flexibleButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; UIBarButtonItem *addButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add)]; _toolbar.items=[NSArray arrayWithObjects:removeButton, flexibleButton, addButton, nil]; }

1. 刪除

在 UITableView 中,無論刪除還是新增,都是透過改變表格的編輯狀態來實現的。在刪除按鈕中設定編輯狀態:

 -(void)remove{ // 用此方法可帶動畫切換編輯狀態 [_tableView setEditing:!_tableView.isEditing animated:true]; }

點擊刪除按鈕後,Cell 左側會出現刪除圖標:

此時點擊左側刪除圖標,右側便出現刪除選項:

我們都知道,向左滑動 Cell 右側也會出現刪除按鈕。實現這功能只要實作代理方法 commitEditingStyle:forRowAtIndexPath:,向左滑動即會顯示刪除按鈕。點擊後便會呼叫此方法,但需注意刪除與新增都走同一個方法,只是第二個參數類型不同。具體刪除實現如下:

 -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ KCContactGroup *group=_contacts[indexPath.section]; KCContact *contact=group.contacts[indexPath.row]; if (editingStyle==UITableViewCellEditingStyleDelete) { [group.contacts removeObject:contact]; // 用局部刷新,兼顧效能與動畫 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom]; // 若該組已無資料則移除該組並刷新整個表格 if (group.contacts.count==0) { [_contacts removeObject:group]; [tableView reloadData]; } } }

這裡再次體現了 MVC 思想:要改 UI,先改資料。同時我們看到了另一個刷新表格的方法 deleteRowsAtIndexPaths:withRowAnimation:,它能在刪除後局部刷新對應單元格。效果如下:

2. 新增

新增與刪除都是設定編輯狀態,具體是新增還是刪除,需依代理方法 editingStyleForRowAtIndexPath: 的回傳值來決定。因此我們定義一個變數記錄點擊了哪個按鈕,在此方法中回傳不同的值。

 -(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{ if (_isInsert) { return UITableViewCellEditingStyleInsert; } return UITableViewCellEditingStyleDelete; } -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ KCContactGroup *group=_contacts[indexPath.section]; KCContact *contact=group.contacts[indexPath.row]; if (editingStyle==UITableViewCellEditingStyleDelete) { [group.contacts removeObject:contact]; [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom]; if (group.contacts.count==0) { [_contacts removeObject:group]; [tableView reloadData]; } }else if(editingStyle==UITableViewCellEditingStyleInsert){ KCContact *newContact=[[KCContact alloc]init]; newContact.firstName=@"first"; newContact.lastName=@"last"; newContact.phoneNumber=@"12345678901"; [group.contacts insertObject:newContact atIndex:indexPath.row]; [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];// 這裡同樣不用 reloadData } }

運行效果如下:

3. 排序

只要實作 moveRowAtIndexPath:toIndexPath: 代理方法,當表格處於編輯狀態時即可排序。

 -(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{ KCContactGroup *sourceGroup=_contacts[sourceIndexPath.section]; KCContact *sourceContact=sourceGroup.contacts[sourceIndexPath.row]; KCContactGroup *destinationGroup=_contacts[destinationIndexPath.section]; [sourceGroup.contacts removeObject:sourceContact]; [destinationGroup.contacts insertObject:sourceContact atIndex:destinationIndexPath.row]; if(sourceGroup.contacts.count==0){ [_contacts removeObject:sourceGroup]; [tableView reloadData]; } }

運行效果如下:

最後歸納幾種常用的表格刷新方法:

- (void)reloadData; 刷新整個表格。

- (void)reloadRowsAtIndexPaths:withRowAnimation: 刷新指定的分組與行。

- (void)reloadSections:withRowAnimation: 刷新指定的分組。

- (void)deleteRowsAtIndexPaths:withRowAnimation: 刪除時刷新指定的行。

- (void)insertRowsAtIndexPaths:withRowAnimation: 新增時刷新指定的行。

七、UITableViewController

很多時候一個 UIViewController 中只有一個 UITableView,因此蘋果官方提供了 UITableViewController。它已實作 UITableView 的資料來源與代理協議,內部定義了一個 tableView 屬性供外部存取,並自動鋪滿整個螢幕、自動伸縮,方便開發。此外它還支援下拉刷新、滾動時固定分組標題等進階功能。

當表格資料特別多、檢索不便時,可以加上搜尋功能。搜尋的原理很簡單:修改模型、刷新表格。下面用 UITableViewController 示範這個功能:

 // KCContactTableViewController.m #define kSearchbarHeight 44 @interface KCContactTableViewController (){ UITableView *_tableView; UISearchBar *_searchBar; NSMutableArray *_contacts; // 聯絡人模型 NSMutableArray *_searchContacts; // 符合條件的搜尋結果 BOOL _isSearching; } @end @implementation KCContactTableViewController - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { if (_isSearching) { return 1; } return _contacts.count; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (_isSearching) { return _searchContacts.count; } KCContactGroup *group1=_contacts[section]; return group1.contacts.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { KCContact *contact=nil; if (_isSearching) { contact=_searchContacts[indexPath.row]; }else{ KCContactGroup *group=_contacts[indexPath.section]; contact=group.contacts[indexPath.row]; } static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1"; UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if(!cell){ cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier]; } cell.textLabel.text=[contact getName]; cell.detailTextLabel.text=contact.phoneNumber; return cell; } -(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ if([_searchBar.text isEqual:@""]){ _isSearching=NO; [self.tableView reloadData]; return; } [self searchDataWithKeyWord:_searchBar.text]; } -(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ [self searchDataWithKeyWord:_searchBar.text]; [_searchBar resignFirstResponder];// 關閉虛擬鍵盤 } -(void)searchDataWithKeyWord:(NSString *)keyWord{ _isSearching=YES; _searchContacts=[NSMutableArray array]; [_contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { KCContactGroup *group=obj; [group.contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { KCContact *contact=obj; if ([contact.firstName.uppercaseString containsString:keyWord.uppercaseString]||[contact.lastName.uppercaseString containsString:keyWord.uppercaseString]||[contact.phoneNumber containsString:keyWord]) { [_searchContacts addObject:contact]; } }]; }]; [self.tableView reloadData]; } -(void)addSearchBar{ CGRect searchBarRect=CGRectMake(0, 0, self.view.frame.size.width, kSearchbarHeight); _searchBar=[[UISearchBar alloc]initWithFrame:searchBarRect]; _searchBar.placeholder=@"Please input key word..."; _searchBar.showsCancelButton=YES; _searchBar.delegate=self; self.tableView.tableHeaderView=_searchBar; } @end

運行效果如下:

上面的搜尋除了用 _contacts 保存聯絡人資料,還專門定義了 _searchContacts 保存搜尋結果。輸入關鍵字時刷新表格,並在資料來源方法中依搜尋狀態決定顯示原始資料還是搜尋結果。

我們發現每次搜尋後都需手動刷新表格,且沒有關鍵字時還要把表格重設為初始狀態——用一個 tableView 顯示兩種狀態的資料,自然提高了邏輯複雜度。為簡化這個過程,可使用 UISearchDisplayController:它內部也有一個 searchResultsTableView,只要把它的資料來源與代理設為當前控制器,就能像 UITableView 一樣載入資料,同時它自帶搜尋監聽方法,不必再手動監聽 UISearchBar 輸入,即可自動刷新其內部表格。

 // KCContactTableViewControllerWithUISearchDisplayController.m @interface KCContactTableViewControllerWithUISearchDisplayController (){ UISearchBar *_searchBar; UISearchDisplayController *_searchDisplayController; NSMutableArray *_contacts; NSMutableArray *_searchContacts; } @end @implementation KCContactTableViewControllerWithUISearchDisplayController - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // 若當前是 UISearchDisplayController 內部的 tableView 則不分組 if (tableView==self.searchDisplayController.searchResultsTableView) { return 1; } return _contacts.count; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (tableView==self.searchDisplayController.searchResultsTableView) { return _searchContacts.count; } KCContactGroup *group1=_contacts[section]; return group1.contacts.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { KCContact *contact=nil; if (tableView==self.searchDisplayController.searchResultsTableView) { contact=_searchContacts[indexPath.row]; }else{ KCContactGroup *group=_contacts[indexPath.section]; contact=group.contacts[indexPath.row]; } static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1"; UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if(!cell){ cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier]; } cell.textLabel.text=[contact getName]; cell.detailTextLabel.text=contact.phoneNumber; return cell; } -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ if (tableView==self.searchDisplayController.searchResultsTableView) { return @"搜尋結果"; } KCContactGroup *group=_contacts[section]; return group.name; } #pragma mark UISearchDisplayController 代理方法 -(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{ [self searchDataWithKeyWord:searchString]; return YES; } -(void)addSearchBar{ _searchBar=[[UISearchBar alloc]init]; [_searchBar sizeToFit]; _searchBar.placeholder=@"Please input key word..."; _searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone; _searchBar.showsCancelButton=YES; _searchBar.delegate=self; self.tableView.tableHeaderView=_searchBar; _searchDisplayController=[[UISearchDisplayController alloc]initWithSearchBar:_searchBar contentsController:self]; _searchDisplayController.delegate=self; _searchDisplayController.searchResultsDataSource=self; _searchDisplayController.searchResultsDelegate=self; [_searchDisplayController setActive:NO animated:YES]; } @end

運行效果如下:

注意:若使用 Storyboard 或 xib 建立上述程式碼,則無需定義 UISearchDisplayController 成員變數,因為每個 UIViewController 中已內建一個 searchDisplayController 物件。

八、MVC 模式

透過 UITableView 的學習,相信大家对 iOS 的 MVC 已有大致了解。在 iOS 中,多數資料來源視圖控件(View)都有一個 dataSource 屬性用於與控制器(Controller)互動,而資料來源一般以資料模型(Model)的形式定義。View 不直接與模型互動,而是透過 Controller 間接讀取資料。

以通訊錄為例,UITableView 作為視圖(View)並不能直接存取模型 Contact,它要顯示聯絡人資訊只能透過控制器(Controller)提供的資料來源方法。而控制器本身擁有視圖控件、可操作視圖,也就是說視圖與控制器之間可以互相存取;模型則既不能存取視圖,也不能存取控制器。具體依賴關係如下圖:

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved