UITableView詳解

在iOS開發中UITableView可以說是使用最廣泛的控件,我們平時使用的軟件中到處都可以看到它的影子,類似於微信、QQ、新浪微博等軟件基本上隨處都是UITableView。當然它的廣泛使用自然離不開它強大的功能,今天這篇文章將針對UITableView重點展開討論。今天的主要內容包括:

1.基本介紹
2.數據源
3.代理
4.性能優化
5.UITableViewCell
6.常用操作
7.UITableViewController
8.MVC模式

基本介紹
UITableView有兩種風格:UITableViewStylePlain和UITableViewStyleGrouped。這兩者操作起來其實並沒有本質區別,只是後者按分組樣式顯示前者按照普通樣式顯示而已。大家先看一下兩者的應用:
 
1>分組樣式
2>不分組樣式
 
大家可以看到在UITableView中數據只有行的概念,並沒有列的概念,因爲在手機操作系統中顯示多列是不利於操作的。UITableView中每行數據都是一個UITableViewCell,在這個控件中爲了顯示更多的信息,iOS已經在其內部設置好了多個子控件以供開發者使用。如果我們查看UITableViewCell的聲明文件可以發現在內部有一個UIView控件(contentView,作爲其他元素的父控件)、兩個UILable控件(textLabel、detailTextLabel)、一個UIImage控件(imageView),分別用於容器、顯示內容、詳情和圖片。使用效果類似於微信、QQ信息列表:
當然,這些子控件並不一定要全部使用,具體操作時可以通過UITableViewCellStyle進行設置,具體每個枚舉表示的意思已經在代碼中進行了註釋:
  1. typedef NS_ENUM(NSInteger, UITableViewCellStyle) { 
  2.     UITableViewCellStyleDefault,    // 左側顯示textLabel(不顯示detailTextLabel),imageView可選(顯示在最左邊) 
  3.     UITableViewCellStyleValue1,        // 左側顯示textLabel、右側顯示detailTextLabel(默認藍色),imageView可選(顯示在最左邊) 
  4.     UITableViewCellStyleValue2,        // 左側依次顯示textLabel(默認藍色)和detailTextLabel,imageView可選(顯示在最左邊) 
  5.     UITableViewCellStyleSubtitle    // 左上方顯示textLabel,左下方顯示detailTextLabel(默認灰色),imageView可選(顯示在最左邊) 
  6. }; 
數據源
由於iOS是遵循MVC模式設計的,很多操作都是通過代理和外界溝通的,但對於數據源控件除了代理還有一個數據源屬性,通過它和外界進行數據交互。 對於UITableView設置完dataSource後需要實現UITableViewDataSource協議,在這個協議中定義了多種 數據操作方法,下面通過創建一個簡單的聯繫人管理進行演示:
首先我們需要創建一個聯繫人模型KCContact
KCContact.h
  1. // 
  2. //  Contact.h 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8.  
  9. #import <Foundation/Foundation.h> 
  10.  
  11. @interface KCContact : NSObject 
  12.  
  13. #pragma mark 姓 
  14. @property (nonatomic,copy) NSString *firstName; 
  15. #pragma mark 名 
  16. @property (nonatomic,copy) NSString *lastName; 
  17. #pragma mark 手機號碼 
  18. @property (nonatomic,copy) NSString *phoneNumber; 
  19.  
  20. #pragma mark 帶參數的構造函數 
  21. -(KCContact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber; 
  22.  
  23. #pragma mark 取得姓名 
  24. -(NSString *)getName; 
  25.  
  26.  
  27. #pragma mark 帶參數的靜態對象初始化方法 
  28. +(KCContact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber; 
  29. @end 
KCContact.m
  1. // 
  2. //  Contact.m 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8.  
  9. #import "KCContact.h" 
  10.  
  11. @implementation KCContact 
  12.  
  13. -(KCContact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber{ 
  14.     if(self=[super init]){ 
  15.         self.firstName=firstName; 
  16.         self.lastName=lastName; 
  17.         self.phoneNumber=phoneNumber; 
  18.     } 
  19.     return self; 
  20.  
  21. -(NSString *)getName{ 
  22.     return [NSString stringWithFormat:@"%@ %@",_lastName,_firstName]; 
  23.  
  24. +(KCContact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber{ 
  25.     KCContact *contact1=[[KCContact alloc]initWithFirstName:firstName andLastName:lastName andPhoneNumber:phoneNumber]; 
  26.     return contact1; 
  27.  
  28. @end 
爲了演示分組顯示我們不妨將一組數據也抽象成模型KCContactGroup
KCContactGroup.h
  1. // 
  2. //  KCContactGroup.h 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8.  
  9. #import <Foundation/Foundation.h> 
  10. #import "KCContact.h" 
  11.  
  12. @interface KCContactGroup : NSObject 
  13.  
  14. #pragma mark 組名 
  15. @property (nonatomic,copy) NSString *name; 
  16.  
  17. #pragma mark 分組描述 
  18. @property (nonatomic,copy) NSString *detail; 
  19.  
  20. #pragma mark 聯繫人 
  21. @property (nonatomic,strong) NSMutableArray *contacts; 
  22.  
  23. #pragma mark 帶參數個構造函數 
  24. -(KCContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts; 
  25.  
  26. #pragma mark 靜態初始化方法 
  27. +(KCContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts; 
  28.  
  29. @end 
KCContactGroup.m
  1. // 
  2. //  KCContactGroup.m 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8.  
  9. #import "KCContactGroup.h" 
  10.  
  11. @implementation KCContactGroup 
  12.  
  13.  
  14. -(KCContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts{ 
  15.     if (self=[super init]) { 
  16.         self.name=name; 
  17.         self.detail=detail; 
  18.         self.contacts=contacts; 
  19.     } 
  20.     return self; 
  21.  
  22. +(KCContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts{ 
  23.     KCContactGroup *group1=[[KCContactGroup alloc]initWithName:name andDetail:detail andContacts:contacts]; 
  24.     return group1; 
  25. @end 
然後在viewDidLoad方法中創建一些模擬數據同時實現數據源協議方法:
KCMainViewController.m
  1. // 
  2. //  KCMainViewController.m 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8.  
  9. #import "KCMainViewController.h" 
  10. #import "KCContact.h" 
  11. #import "KCContactGroup.h" 
  12.  
  13. @interface KCMainViewController ()<UITableViewDataSource>{ 
  14.     UITableView *_tableView; 
  15.     NSMutableArray *_contacts;//聯繫人模型 
  16.  
  17. @end 
  18.  
  19. @implementation KCMainViewController 
  20.  
  21. - (void)viewDidLoad { 
  22.     [super viewDidLoad]; 
  23.      
  24.     //初始化數據 
  25.     [self initData]; 
  26.      
  27.     //創建一個分組樣式的UITableView 
  28.     _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped]; 
  29.      
  30.     //設置數據源,注意必須實現對應的UITableViewDataSource協議 
  31.     _tableView.dataSource=self; 
  32.      
  33.     [self.view addSubview:_tableView]; 
  34.  
  35. #pragma mark 加載數據 
  36. -(void)initData{ 
  37.     _contacts=[[NSMutableArray alloc]init]; 
  38.      
  39.     KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"]; 
  40.     KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"]; 
  41.     KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]]; 
  42.     [_contacts addObject:group1]; 
  43.      
  44.  
  45.      
  46.     KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"]; 
  47.     KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"]; 
  48.     KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"]; 
  49.     KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]]; 
  50.     [_contacts addObject:group2]; 
  51.      
  52.      
  53.      
  54.     KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"]; 
  55.     KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"]; 
  56.  
  57.     KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]]; 
  58.     [_contacts addObject:group3]; 
  59.      
  60.      
  61.     KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"]; 
  62.     KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"]; 
  63.     KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"]; 
  64.     KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"]; 
  65.     KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"]; 
  66.     KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]]; 
  67.     [_contacts addObject:group4]; 
  68.      
  69.      
  70.     KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"]; 
  71.     KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"]; 
  72.     KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"]; 
  73.     KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]]; 
  74.     [_contacts addObject:group5]; 
  75.  
  76.  
  77. #pragma mark - 數據源方法 
  78. #pragma mark 返回分組數 
  79. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
  80.     NSLog(@"計算分組數"); 
  81.     return _contacts.count; 
  82.  
  83. #pragma mark 返回每組行數 
  84. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
  85.     NSLog(@"計算每組(組%i)行數",section); 
  86.     KCContactGroup *group1=_contacts[section]; 
  87.     return group1.contacts.count; 
  88.  
  89. #pragma mark返回每行的單元格 
  90. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
  91.     //NSIndexPath是一個結構體,記錄了組和行信息 
  92.     NSLog(@"生成單元格(組:%i,行%i)",indexPath.section,indexPath.row); 
  93.     KCContactGroup *group=_contacts[indexPath.section]; 
  94.     KCContact *contact=group.contacts[indexPath.row]; 
  95.     UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil]; 
  96.     cell.textLabel.text=[contact getName]; 
  97.     cell.detailTextLabel.text=contact.phoneNumber; 
  98.     return cell; 
  99.  
  100. #pragma mark 返回每組頭標題名稱 
  101. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ 
  102.     NSLog(@"生成組(組%i)名稱",section); 
  103.     KCContactGroup *group=_contacts[section]; 
  104.     return group.name; 
  105.  
  106. #pragma mark 返回每組尾部說明 
  107. -(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{ 
  108.     NSLog(@"生成尾部(組%i)詳情",section); 
  109.     KCContactGroup *group=_contacts[section]; 
  110.     return group.detail; 
  111. @end 
運行可以看到如下效果:
大家在使用iPhone通訊錄時會發現右側可以按字母檢索,使用起來很方便,其實這個功能使用UITableView實現很簡單,只要實現數據源協議的一個方法,構建一個分組標題的數組即可實現。數組元素的內容和組標題內容未必完全一致,UITableView是按照數組元素的索引和每組數據索引順序來定位的而不是按內容查找。
  1. #pragma mark 返回每組標題索引 
  2. -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{ 
  3.     NSLog(@"生成組索引"); 
  4.     NSMutableArray *indexs=[[NSMutableArray alloc]init]; 
  5.     for(KCContactGroup *group in _contacts){ 
  6.         [indexs addObject:group.name]; 
  7.     } 
  8.     return indexs; 
效果如下:
需要注意的是上面幾個重點方法的執行順序,請看下圖:
值得指出的是生成單元格的方法並不是一次全部調用,而是隻會生產當前顯示在界面上的單元格,當用戶滾動操作時再顯示其他單元格。
 
注意:隨着我們的應用越來越複雜,可能經常需要調試程序,在iOS中默認情況下不能定位到錯誤代碼行,我們可以通過如下設置讓程序定位到出錯代碼行:Show the Breakpoint  navigator—Add Exception breakpoint。
 
代理
上面我們已經看到通訊錄的簡單實現,但是我們發現單元格高度、分組標題高度以及尾部說明的高度都需要調整,此時就需要使用代理方法。UITableView代理方法有很多,例如監聽單元格顯示週期、監聽單元格選擇編輯操作、設置是否高亮顯示單元格、設置行高等。
1.設置行高
  1. #pragma mark - 代理方法 
  2. #pragma mark 設置分組標題內容高度 
  3. -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{ 
  4.     if(section==0){ 
  5.         return 50; 
  6.     } 
  7.     return 40; 
  8.  
  9. #pragma mark 設置每行高度(每行高度可以不一樣) 
  10. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 
  11.     return 45; 
  12.  
  13. #pragma mark 設置尾部說明內容高度 
  14. -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{ 
  15.     return 40; 
2.監聽點擊
在iOS中點擊某聯繫個人就可以呼叫這個聯繫人,這時就需要監聽點擊操作,這裏就不演示呼叫聯繫人操作了,我們演示一下修改人員信息的操作。
KCMainViewContrller.m
  1. // 
  2. //  KCMainViewController.m 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8.  
  9. #import "KCMainViewController.h" 
  10. #import "KCContact.h" 
  11. #import "KCContactGroup.h" 
  12.  
  13. @interface KCMainViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>{ 
  14.     UITableView *_tableView; 
  15.     NSMutableArray *_contacts;//聯繫人模型 
  16.     NSIndexPath *_selectedIndexPath;//當前選中的組和行 
  17.  
  18. @end 
  19.  
  20. @implementation KCMainViewController 
  21.  
  22. - (void)viewDidLoad { 
  23.     [super viewDidLoad]; 
  24.      
  25.     //初始化數據 
  26.     [self initData]; 
  27.      
  28.     //創建一個分組樣式的UITableView 
  29.     _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped]; 
  30.      
  31.     //設置數據源,注意必須實現對應的UITableViewDataSource協議 
  32.     _tableView.dataSource=self; 
  33.     //設置代理 
  34.     _tableView.delegate=self; 
  35.      
  36.     [self.view addSubview:_tableView]; 
  37.  
  38. #pragma mark 加載數據 
  39. -(void)initData{ 
  40.     _contacts=[[NSMutableArray alloc]init]; 
  41.      
  42.     KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"]; 
  43.     KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"]; 
  44.     KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]]; 
  45.     [_contacts addObject:group1]; 
  46.      
  47.  
  48.      
  49.     KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"]; 
  50.     KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"]; 
  51.     KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"]; 
  52.     KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]]; 
  53.     [_contacts addObject:group2]; 
  54.      
  55.      
  56.      
  57.     KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"]; 
  58.     KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"]; 
  59.  
  60.     KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]]; 
  61.     [_contacts addObject:group3]; 
  62.      
  63.      
  64.     KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"]; 
  65.     KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"]; 
  66.     KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"]; 
  67.     KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"]; 
  68.     KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"]; 
  69.     KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]]; 
  70.     [_contacts addObject:group4]; 
  71.      
  72.      
  73.     KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"]; 
  74.     KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"]; 
  75.     KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"]; 
  76.     KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]]; 
  77.     [_contacts addObject:group5]; 
  78.  
  79.  
  80. #pragma mark - 數據源方法 
  81. #pragma mark 返回分組數 
  82. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
  83.     NSLog(@"計算分組數"); 
  84.     return _contacts.count; 
  85.  
  86. #pragma mark 返回每組行數 
  87. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
  88.     NSLog(@"計算每組(組%i)行數",section); 
  89.     KCContactGroup *group1=_contacts[section]; 
  90.     return group1.contacts.count; 
  91.  
  92. #pragma mark返回每行的單元格 
  93. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
  94.     //NSIndexPath是一個對象,記錄了組和行信息 
  95.     NSLog(@"生成單元格(組:%i,行%i)",indexPath.section,indexPath.row); 
  96.     KCContactGroup *group=_contacts[indexPath.section]; 
  97.     KCContact *contact=group.contacts[indexPath.row]; 
  98.     UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil]; 
  99.     cell.textLabel.text=[contact getName]; 
  100.     cell.detailTextLabel.text=contact.phoneNumber; 
  101.     return cell; 
  102.  
  103. #pragma mark 返回每組頭標題名稱 
  104. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ 
  105.     NSLog(@"生成組(組%i)名稱",section); 
  106.     KCContactGroup *group=_contacts[section]; 
  107.     return group.name; 
  108.  
  109. #pragma mark 返回每組尾部說明 
  110. -(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{ 
  111.     NSLog(@"生成尾部(組%i)詳情",section); 
  112.     KCContactGroup *group=_contacts[section]; 
  113.     return group.detail; 
  114.  
  115. #pragma mark 返回每組標題索引 
  116. -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{ 
  117.     NSLog(@"生成組索引"); 
  118.     NSMutableArray *indexs=[[NSMutableArray alloc]init]; 
  119.     for(KCContactGroup *group in _contacts){ 
  120.         [indexs addObject:group.name]; 
  121.     } 
  122.     return indexs; 
  123.  
  124. #pragma mark - 代理方法 
  125. #pragma mark 設置分組標題內容高度 
  126. -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{ 
  127.     if(section==0){ 
  128.         return 50; 
  129.     } 
  130.     return 40; 
  131.  
  132. #pragma mark 設置每行高度(每行高度可以不一樣) 
  133. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 
  134.     return 45; 
  135.  
  136. #pragma mark 設置尾部說明內容高度 
  137. -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{ 
  138.     return 40; 
  139.  
  140. #pragma mark 點擊行 
  141. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
  142.     _selectedIndexPath=indexPath; 
  143.     KCContactGroup *group=_contacts[indexPath.section]; 
  144.     KCContact *contact=group.contacts[indexPath.row]; 
  145.     //創建彈出窗口 
  146.     UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"System Info" message:[contact getName] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; 
  147.     alert.alertViewStyle=UIAlertViewStylePlainTextInput; //設置窗口內容樣式 
  148.     UITextField *textField= [alert textFieldAtIndex:0]; //取得文本框 
  149.     textField.text=contact.phoneNumber; //設置文本框內容 
  150.     [alert show]; //顯示窗口 
  151.  
  152. #pragma mark 窗口的代理方法,用戶保存數據 
  153. -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
  154.     //當點擊了第二個按鈕(OK) 
  155.     if (buttonIndex==1) { 
  156.         UITextField *textField= [alertView textFieldAtIndex:0]; 
  157.         //修改模型數據 
  158.         KCContactGroup *group=_contacts[_selectedIndexPath.section]; 
  159.         KCContact *contact=group.contacts[_selectedIndexPath.row]; 
  160.         contact.phoneNumber=textField.text; 
  161.         //刷新表格 
  162.         [_tableView reloadData]; 
  163.     } 
  164.  
  165. #pragma mark 重寫狀態樣式方法 
  166. -(UIStatusBarStyle)preferredStatusBarStyle{ 
  167.     return UIStatusBarStyleLightContent; 
  168. @end 
在上面的代碼中我們通過修改模型來改變UI顯示,這種方式是經典的MVC應用,在後面的代碼中會經常看到。當然UI的刷新使用了UITableView的reloadData方法,該方法會重新調用數據源方法,包括計算分組、計算每個分組的行數,生成單元格等刷新整個UITableView。當然這種方式在實際開發中是不可取的,我們不可能因爲修改了一個人的信息就刷新整個UITableViewView,此時我們需要採用局部刷新。局部刷新使用起來很簡單,只需要調用UITableView的另外一個方法:
  1. #pragma mark 窗口的代理方法,用戶保存數據 
  2. -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
  3.     //當點擊了第二個按鈕(OK) 
  4.     if (buttonIndex==1) { 
  5.         UITextField *textField= [alertView textFieldAtIndex:0]; 
  6.         //修改模型數據 
  7.         KCContactGroup *group=_contacts[_selectedIndexPath.section]; 
  8.         KCContact *contact=group.contacts[_selectedIndexPath.row]; 
  9.         contact.phoneNumber=textField.text; 
  10.         //刷新表格 
  11.         NSArray *indexPaths=@[_selectedIndexPath];//需要局部刷新的單元格的組、行 
  12.         [_tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];//後面的參數代表更新時的動畫 
  13.     } 
性能優化
前面已經說過UITableView中的單元格cell是在顯示到用戶可視區域後創建的,那麼如果用戶往下滾動就會繼續創建顯示在屏幕上的單元格,如果用戶向上滾動返回到查看過的內容時同樣會重新創建之前已經創建過的單元格。如此一來即使UITableView的內容不是太多,如果用戶反覆的上下滾動,內存也會瞬間飆升,更何況很多時候UITableView的內容是很多的(例如微博展示列表,基本向下滾動是沒有底限的)。
 
前面一節中我們曾經提到過如何優化UIScrollView,當時就是利用有限的UIImageView動態切換其內容來儘可能減少資源佔用。同樣的,在UITableView中也可以採用類似的方式,只是這時我們不是在滾動到指定位置後更改滾動的位置而是要將當前沒有顯示的Cell重新顯示在將要顯示的Cell的位置然後更新其內容。原因就是UITableView中的Cell結構佈局可能是不同的,通過重新定位是不可取的,而是需要重用已經不再界面顯示的已創建過的Cell。
 
當然,聽起來這麼做比較複雜,其實實現起來很簡單,因爲UITableView已經爲我們實現了這種機制。在UITableView內部有一個緩存池,初始化時使用initWithStyle:(UITableViewCellStyle) reuseIdentifier:(NSString *)方法指定一個可重用標識,就可以將這個cell放到緩存池。然後在使用時使用指定的標識去緩存池中取得對應的cell然後修改cell內容即可。
 
上面的代碼中已經打印了cell的地址,如果大家運行測試上下滾動UITableView會發現滾動時創建的cell地址是初始化時已經創建的。
 
這裏再次給大家強調兩點:
1. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)方法調用很頻繁,無論是初始化、上下滾動、刷新都會調用此方法,所有在這裏執行的操作一定要注意性能;
2. 可重用標識可以有多個,如果在UITableView中有多類結構不同的Cell,可以通過這個標識進行緩存和重新。
 
UITableViewCell
1.自帶的UITableViewCell
UITableViewCell是構建一個UITableView的基礎,在UITableViewCell內部有一個UIView控件作爲其他內容的容器,它上面有一個UIImageView和兩個UILabel,通過UITableViewCellStyle屬性可以對其樣式進行控制。其結構如下:
有時候我們會發現很多UITableViewCell右側可以顯示不同的圖標,在iOS中稱之爲訪問器,點擊可以觸發不同的事件,例如設置功能:
要設置這些圖標只需要設置UITableViewCell的accesoryType屬性,這是一個枚舉類型具體含義如下:
  1. typedef NS_ENUM(NSInteger, UITableViewCellAccessoryType) { 
  2.     UITableViewCellAccessoryNone,                   // 不顯示任何圖標 
  3.     UITableViewCellAccessoryDisclosureIndicator,    // 跳轉指示圖標 
  4.     UITableViewCellAccessoryDetailDisclosureButton, // 內容詳情圖標和跳轉指示圖標 
  5.     UITableViewCellAccessoryCheckmark,              // 勾選圖標 
  6.     UITableViewCellAccessoryDetailButton NS_ENUM_AVAILABLE_IOS(7_0) // 內容詳情圖標 
  7. }; 
例如在最近通話中我們通常設置爲詳情圖標,點擊可以查看聯繫人詳情:
很明顯iOS設置中第一個accessoryType不在枚舉之列,右側的訪問器類型是UISwitch控件,那麼如何顯示自定義的訪問器呢?其實只要設置UITableViewCell的accessoryView即可,它支持任何UIView控件。假設我們在通訊錄每組第一行放一個UISwitch,同時切換時可以輸出對應信息:
  1. // 
  2. //  KCMainViewController.m 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8.  
  9. #import "KCMainViewController.h" 
  10. #import "KCContact.h" 
  11. #import "KCContactGroup.h" 
  12.  
  13. @interface KCMainViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>{ 
  14.     UITableView *_tableView; 
  15.     NSMutableArray *_contacts;//聯繫人模型 
  16.     NSIndexPath *_selectedIndexPath;//當前選中的組和行 
  17.  
  18. @end 
  19.  
  20. @implementation KCMainViewController 
  21.  
  22. - (void)viewDidLoad { 
  23.     [super viewDidLoad]; 
  24.      
  25.     //初始化數據 
  26.     [self initData]; 
  27.      
  28.     //創建一個分組樣式的UITableView 
  29.     _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped]; 
  30.      
  31.     //設置數據源,注意必須實現對應的UITableViewDataSource協議 
  32.     _tableView.dataSource=self; 
  33.     //設置代理 
  34.     _tableView.delegate=self; 
  35.      
  36.     [self.view addSubview:_tableView]; 
  37.  
  38. #pragma mark 加載數據 
  39. -(void)initData{ 
  40.     _contacts=[[NSMutableArray alloc]init]; 
  41.      
  42.     KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"]; 
  43.     KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"]; 
  44.     KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]]; 
  45.     [_contacts addObject:group1]; 
  46.      
  47.  
  48.      
  49.     KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"]; 
  50.     KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"]; 
  51.     KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"]; 
  52.     KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]]; 
  53.     [_contacts addObject:group2]; 
  54.      
  55.      
  56.      
  57.     KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"]; 
  58.     KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"]; 
  59.  
  60.     KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]]; 
  61.     [_contacts addObject:group3]; 
  62.      
  63.      
  64.     KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"]; 
  65.     KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"]; 
  66.     KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"]; 
  67.     KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"]; 
  68.     KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"]; 
  69.     KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]]; 
  70.     [_contacts addObject:group4]; 
  71.      
  72.      
  73.     KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"]; 
  74.     KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"]; 
  75.     KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"]; 
  76.     KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]]; 
  77.     [_contacts addObject:group5]; 
  78.  
  79.  
  80. #pragma mark - 數據源方法 
  81. #pragma mark 返回分組數 
  82. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
  83.     NSLog(@"計算分組數"); 
  84.     return _contacts.count; 
  85.  
  86. #pragma mark 返回每組行數 
  87. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
  88.     NSLog(@"計算每組(組%i)行數",section); 
  89.     KCContactGroup *group1=_contacts[section]; 
  90.     return group1.contacts.count; 
  91.  
  92. #pragma mark返回每行的單元格 
  93. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
  94.     //NSIndexPath是一個對象,記錄了組和行信息 
  95.     NSLog(@"生成單元格(組:%i,行%i)",indexPath.section,indexPath.row); 
  96.     KCContactGroup *group=_contacts[indexPath.section]; 
  97.     KCContact *contact=group.contacts[indexPath.row]; 
  98.      
  99.     //由於此方法調用十分頻繁,cell的標示聲明成靜態變量有利於性能優化 
  100.     static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1"
  101.     static NSString *cellIdentifierForFirstRow=@"UITableViewCellIdentifierKeyWithSwitch"
  102.     //首先根據標示去緩存池取 
  103.     UITableViewCell *cell; 
  104.     if (indexPath.row==0) { 
  105.         cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifierForFirstRow]; 
  106.     }else
  107.         cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
  108.     } 
  109.     //如果緩存池沒有取到則重新創建並放到緩存池中 
  110.     if(!cell){ 
  111.         if (indexPath.row==0) { 
  112.             cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifierForFirstRow]; 
  113.             UISwitch *sw=[[UISwitch alloc]init]; 
  114.             [sw addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventValueChanged]; 
  115.             cell.accessoryView=sw; 
  116.  
  117.         }else
  118.             cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier]; 
  119.             cell.accessoryType=UITableViewCellAccessoryDetailButton; 
  120.         } 
  121.     } 
  122.      
  123.     if(indexPath.row==0){ 
  124.         ((UISwitch *)cell.accessoryView).tag=indexPath.section; 
  125.     } 
  126.      
  127.     cell.textLabel.text=[contact getName]; 
  128.     cell.detailTextLabel.text=contact.phoneNumber; 
  129.     NSLog(@"cell:%@",cell); 
  130.      
  131.     return cell; 
  132.  
  133. #pragma mark 返回每組頭標題名稱 
  134. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ 
  135.     NSLog(@"生成組(組%i)名稱",section); 
  136.     KCContactGroup *group=_contacts[section]; 
  137.     return group.name; 
  138.  
  139. #pragma mark 返回每組尾部說明 
  140. -(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{ 
  141.     NSLog(@"生成尾部(組%i)詳情",section); 
  142.     KCContactGroup *group=_contacts[section]; 
  143.     return group.detail; 
  144.  
  145. #pragma mark 返回每組標題索引 
  146. -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{ 
  147.     NSLog(@"生成組索引"); 
  148.     NSMutableArray *indexs=[[NSMutableArray alloc]init]; 
  149.     for(KCContactGroup *group in _contacts){ 
  150.         [indexs addObject:group.name]; 
  151.     } 
  152.     return indexs; 
  153.  
  154. #pragma mark - 代理方法 
  155. #pragma mark 設置分組標題內容高度 
  156. -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{ 
  157.     if(section==0){ 
  158.         return 50; 
  159.     } 
  160.     return 40; 
  161.  
  162. #pragma mark 設置每行高度(每行高度可以不一樣) 
  163. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 
  164.     return 45; 
  165.  
  166. #pragma mark 設置尾部說明內容高度 
  167. -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{ 
  168.     return 40; 
  169.  
  170. #pragma mark 點擊行 
  171. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
  172.     _selectedIndexPath=indexPath; 
  173.     KCContactGroup *group=_contacts[indexPath.section]; 
  174.     KCContact *contact=group.contacts[indexPath.row]; 
  175.     //創建彈出窗口 
  176.     UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"System Info" message:[contact getName] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; 
  177.     alert.alertViewStyle=UIAlertViewStylePlainTextInput; //設置窗口內容樣式 
  178.     UITextField *textField= [alert textFieldAtIndex:0]; //取得文本框 
  179.     textField.text=contact.phoneNumber; //設置文本框內容 
  180.     [alert show]; //顯示窗口 
  181.  
  182. #pragma mark 窗口的代理方法,用戶保存數據 
  183. -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
  184.     //當點擊了第二個按鈕(OK) 
  185.     if (buttonIndex==1) { 
  186.         UITextField *textField= [alertView textFieldAtIndex:0]; 
  187.         //修改模型數據 
  188.         KCContactGroup *group=_contacts[_selectedIndexPath.section]; 
  189.         KCContact *contact=group.contacts[_selectedIndexPath.row]; 
  190.         contact.phoneNumber=textField.text; 
  191.         //刷新表格 
  192.         NSArray *indexPaths=@[_selectedIndexPath];//需要局部刷新的單元格的組、行 
  193.         [_tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];//後面的參數代碼更新時的動畫 
  194.     } 
  195.  
  196.  
  197. #pragma mark 重寫狀態樣式方法 
  198. -(UIStatusBarStyle)preferredStatusBarStyle{ 
  199.     return UIStatusBarStyleLightContent; 
  200.  
  201.  
  202. #pragma mark 切換開關轉化事件 
  203. -(void)switchValueChange:(UISwitch *)sw{ 
  204.     NSLog(@"section:%i,switch:%i",sw.tag, sw.on); 
  205. @end 
最終運行效果:
注意:
1.由於此時我們需要兩種UITableViewCell樣式,考慮到性能我們需要在緩存池緩存兩種Cell。
2.UISwitch繼承於UIControl而不是UIView(當然UIControl最終也是繼承於UIView),繼承於UIControl的控件使用addTarget添加對應事件而不是代理,同時有“是否可用”、“是否高亮”、“是否選中”等屬性;
3.上面代碼中如果有些UITableViewCell的UISwitch設置爲on當其他控件重用時狀態也是on,解決這個問題可以在模型中設置對應的屬性記錄其狀態,在生成cell時設置當前狀態(爲了儘可能簡化上面的代碼這裏就不再修復這個問題);
 
2.自定義UITableViewCell
雖然系統自帶的UITableViewCell已經夠強大了,但是很多時候這並不能滿足我們的需求。例如新浪微博的Cell就沒有那麼簡單:
沒錯,這個界面佈局也是UITableView實現的,其中的內容就是UITableViewCell,只是這個UITableViewCell是用戶自定義實現的。當然要實現上面的UITableViewCell三言兩語我們是說不完的,這裏我們實現一個簡化版本,界面原型如下:
我們對具體控件進行拆分:
在這個界面中有2個UIImageView控件和4個UILabel,整個界面顯示效果類似於新浪微博的消息內容界面,但是又在新浪微博基礎上進行了精簡以至於利用現有知識能夠順利開發出來。
在前面的內容中我們的數據都是手動構建的,在實際開發中自然不會這麼做,這裏我們不妨將微博數據存儲到plist文件中然後從plist文件讀取數據構建模型對象(實際開發微博當然需要進行網絡數據請求,這裏只是進行模擬就不再演示網絡請求的內容)。假設plist文件內容如下:
接下來就定義一個KCStatusTableViewCell實現UITableViewCell,一般實現自定義UITableViewCell需要分爲兩步:第一初始化控件;第二設置數據,重新設置控件frame。原因就是自定義Cell一般無法固定高度,很多時候高度需要隨着內容改變。此外由於在單元格內部是無法控制單元格高度的,因此一般會定義一個高度屬性用於在UITableView的代理事件中設置每個單元格高度。
 
首先看一下微博模型KCStatus,這個模型主要的方法就是根據plist字典內容生成微博對象:
KCStatus.h
  1. // 
  2. //  KCStatus.h 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8.  
  9. #import <Foundation/Foundation.h> 
  10.  
  11. @interface KCStatus : NSObject 
  12.  
  13. #pragma mark - 屬性 
  14. @property (nonatomic,assign) long long Id;//微博id 
  15. @property (nonatomic,copy) NSString *profileImageUrl;//頭像 
  16. @property (nonatomic,copy) NSString *userName;//發送用戶 
  17. @property (nonatomic,assign) NSString *mbtype;//會員類型 
  18. @property (nonatomic,copy) NSString *createdAt;//創建時間 
  19. @property (nonatomic,copy) NSString *source;//設備來源 
  20. @property (nonatomic,copy) NSString *text;//微博內容 
  21.  
  22.  
  23.  
  24. #pragma mark - 方法 
  25. #pragma mark 根據字典初始化微博對象 
  26. -(KCStatus *)initWithDictionary:(NSDictionary *)dic; 
  27.  
  28. #pragma mark 初始化微博對象(靜態方法) 
  29. +(KCStatus *)statusWithDictionary:(NSDictionary *)dic; 
  30. @end 
KCStatus.m
  1. // 
  2. //  KCStatus.m 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8.  
  9. #import "KCStatus.h" 
  10.  
  11. @implementation KCStatus 
  12.  
  13. #pragma mark 根據字典初始化微博對象 
  14. -(KCStatus *)initWithDictionary:(NSDictionary *)dic{ 
  15.     if(self=[super init]){ 
  16.         self.Id=[dic[@"Id"] longLongValue]; 
  17.         self.profileImageUrl=dic[@"profileImageUrl"]; 
  18.         self.userName=dic[@"userName"]; 
  19.         self.mbtype=dic[@"mbtype"]; 
  20.         self.createdAt=dic[@"createdAt"]; 
  21.         self.source=dic[@"source"]; 
  22.         self.text=dic[@"text"]; 
  23.     } 
  24.     return self; 
  25.  
  26. #pragma mark 初始化微博對象(靜態方法) 
  27. +(KCStatus *)statusWithDictionary:(NSDictionary *)dic{ 
  28.     KCStatus *status=[[KCStatus alloc]initWithDictionary:dic]; 
  29.     return status; 
  30.  
  31. -(NSString *)source{ 
  32.     return [NSString stringWithFormat:@"來自 %@",_source]; 
  33. @end 
然後看一下自定義的Cell
KCStatusTableViewCell.h
  1. // 
  2. //  KCStatusTableViewCell.h 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8.  
  9. #import <UIKit/UIKit.h> 
  10. @class KCStatus; 
  11.  
  12. @interface KCStatusTableViewCell : UITableViewCell 
  13.  
  14. #pragma mark 微博對象 
  15. @property (nonatomic,strong) KCStatus *status; 
  16.  
  17. #pragma mark 單元格高度 
  18. @property (assign,nonatomic) CGFloat height; 
  19.  
  20. @end 
KCStatusTableViewCell.m
  1. // 
  2. //  KCStatusTableViewCell.m 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8.  
  9. #import "KCStatusTableViewCell.h" 
  10. #import "KCStatus.h" 
  11. #define KCColor(r,g,b) [UIColor colorWithHue:r/255.0 saturation:g/255.0 brightness:b/255.0 alpha:1] //顏色宏定義 
  12. #define kStatusTableViewCellControlSpacing 10 //控件間距 
  13. #define kStatusTableViewCellBackgroundColor KCColor(251,251,251) 
  14. #define kStatusGrayColor KCColor(50,50,50) 
  15. #define kStatusLightGrayColor KCColor(120,120,120) 
  16.  
  17. #define kStatusTableViewCellAvatarWidth 40 //頭像寬度 
  18. #define kStatusTableViewCellAvatarHeight kStatusTableViewCellAvatarWidth 
  19. #define kStatusTableViewCellUserNameFontSize 14 
  20. #define kStatusTableViewCellMbTypeWidth 13 //會員圖標寬度 
  21. #define kStatusTableViewCellMbTypeHeight kStatusTableViewCellMbTypeWidth 
  22. #define kStatusTableViewCellCreateAtFontSize 12 
  23. #define kStatusTableViewCellSourceFontSize 12 
  24. #define kStatusTableViewCellTextFontSize 14 
  25.  
  26.  
  27. @interface KCStatusTableViewCell(){ 
  28.     UIImageView *_avatar;//頭像 
  29.     UIImageView *_mbType;//會員類型 
  30.     UILabel *_userName; 
  31.     UILabel *_createAt; 
  32.     UILabel *_source; 
  33.     UILabel *_text; 
  34.  
  35. @end 
  36.  
  37. @implementation KCStatusTableViewCell 
  38.  
  39. - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { 
  40.     self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
  41.     if (self) { 
  42.         [self initSubView]; 
  43.     } 
  44.     return self; 
  45.  
  46. #pragma mark 初始化視圖 
  47. -(void)initSubView{ 
  48.     //頭像控件 
  49.     _avatar=[[UIImageView alloc]init]; 
  50.     [self addSubview:_avatar]; 
  51.     //用戶名 
  52.     _userName=[[UILabel alloc]init]; 
  53.     _userName.textColor=kStatusGrayColor; 
  54.     _userName.font=[UIFont systemFontOfSize:kStatusTableViewCellUserNameFontSize]; 
  55.     [self addSubview:_userName]; 
  56.     //會員類型 
  57.     _mbType=[[UIImageView alloc]init]; 
  58.     [self addSubview:_mbType]; 
  59.     //日期 
  60.     _createAt=[[UILabel alloc]init]; 
  61.     _createAt.textColor=kStatusLightGrayColor; 
  62.     _createAt.font=[UIFont systemFontOfSize:kStatusTableViewCellCreateAtFontSize]; 
  63.     [self addSubview:_createAt]; 
  64.     //設備 
  65.     _source=[[UILabel alloc]init]; 
  66.     _source.textColor=kStatusLightGrayColor; 
  67.     _source.font=[UIFont systemFontOfSize:kStatusTableViewCellSourceFontSize]; 
  68.     [self addSubview:_source]; 
  69.     //內容 
  70.     _text=[[UILabel alloc]init]; 
  71.     _text.textColor=kStatusGrayColor; 
  72.     _text.font=[UIFont systemFontOfSize:kStatusTableViewCellTextFontSize]; 
  73.     _text.numberOfLines=0; 
  74. //    _text.lineBreakMode=NSLineBreakByWordWrapping; 
  75.     [self addSubview:_text]; 
  76.  
  77. #pragma mark 設置微博 
  78. -(void)setStatus:(KCStatus *)status{ 
  79.     //設置頭像大小和位置 
  80.     CGFloat avatarX=10,avatarY=10; 
  81.     CGRect avatarRect=CGRectMake(avatarX, avatarY, kStatusTableViewCellAvatarWidth, kStatusTableViewCellAvatarHeight); 
  82.     _avatar.image=[UIImage imageNamed:status.profileImageUrl]; 
  83.     _avatar.frame=avatarRect; 
  84.      
  85.      
  86.     //設置會員圖標大小和位置 
  87.     CGFloat userNameX= CGRectGetMaxX(_avatar.frame)+kStatusTableViewCellControlSpacing ; 
  88.     CGFloat userNameY=avatarY; 
  89.     //根據文本內容取得文本佔用空間大小 
  90.     CGSize userNameSize=[status.userName sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:kStatusTableViewCellUserNameFontSize]}]; 
  91.     CGRect userNameRect=CGRectMake(userNameX, userNameY, userNameSize.width,userNameSize.height); 
  92.     _userName.text=status.userName; 
  93.     _userName.frame=userNameRect; 
  94.      
  95.      
  96.     //設置會員圖標大小和位置 
  97.     CGFloat mbTypeX=CGRectGetMaxX(_userName.frame)+kStatusTableViewCellControlSpacing; 
  98.     CGFloat mbTypeY=avatarY; 
  99.     CGRect mbTypeRect=CGRectMake(mbTypeX, mbTypeY, kStatusTableViewCellMbTypeWidth, kStatusTableViewCellMbTypeHeight); 
  100.     _mbType.image=[UIImage imageNamed:status.mbtype]; 
  101.     _mbType.frame=mbTypeRect; 
  102.      
  103.      
  104.     //設置發佈日期大小和位置 
  105.     CGSize createAtSize=[status.createdAt sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kStatusTableViewCellCreateAtFontSize]}]; 
  106.     CGFloat createAtX=userNameX; 
  107.     CGFloat createAtY=CGRectGetMaxY(_avatar.frame)-createAtSize.height; 
  108.     CGRect createAtRect=CGRectMake(createAtX, createAtY, createAtSize.width, createAtSize.height); 
  109.     _createAt.text=status.createdAt; 
  110.     _createAt.frame=createAtRect; 
  111.      
  112.      
  113.     //設置設備信息大小和位置 
  114.     CGSize sourceSize=[status.source sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kStatusTableViewCellSourceFontSize]}]; 
  115.     CGFloat sourceX=CGRectGetMaxX(_createAt.frame)+kStatusTableViewCellControlSpacing; 
  116.     CGFloat sourceY=createAtY; 
  117.     CGRect sourceRect=CGRectMake(sourceX, sourceY, sourceSize.width,sourceSize.height); 
  118.     _source.text=status.source; 
  119.     _source.frame=sourceRect; 
  120.      
  121.      
  122.     //設置微博內容大小和位置 
  123.     CGFloat textX=avatarX; 
  124.     CGFloat textY=CGRectGetMaxY(_avatar.frame)+kStatusTableViewCellControlSpacing; 
  125.     CGFloat textWidth=self.frame.size.width-kStatusTableViewCellControlSpacing*2; 
  126.     CGSize textSize=[status.text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:kStatusTableViewCellTextFontSize]} context:nil].size; 
  127.     CGRect textRect=CGRectMake(textX, textY, textSize.width, textSize.height); 
  128.     _text.text=status.text; 
  129.     _text.frame=textRect; 
  130.      
  131.     _height=CGRectGetMaxY(_text.frame)+kStatusTableViewCellControlSpacing; 
  132.  
  133. #pragma mark 重寫選擇事件,取消選中 
  134. -(void)setSelected:(BOOL)selected animated:(BOOL)animated{ 
  135.      
  136. @end 
這是我們自定義Cell這個例子的核心,自定義Cell分爲兩個步驟:首先要進行各種控件的初始化工作,這個過程中只要將控件放到Cell的View中同時設置控件顯示內容的格式(字體大小、顏色等)即可;然後在數據對象設置方法中進行各個控件的佈局(大小、位置)。在代碼中有幾點需要重點提示大家:
1).對於單行文本數據的顯示調用+ (UIFont *)systemFontOfSize:(CGFloat)fontSize;方法來得到文本寬度和高度。
2).對於多行文本數據的顯示調用- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context ;方法來得到文本寬度和高度;同時注意在此之前需要設置文本控件的numberOfLines屬性爲0。
3).通常我們會在自定義Cell中設置一個高度屬性,用於外界方法調用,因爲Cell內部設置Cell的高度是沒有用的,UITableViewCell在初始化時會重新設置高度。
 
最後我們看一下自定義Cell的使用過程:
KCStatusViewController.m
  1. // 
  2. //  KCCutomCellViewController.m 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8.  
  9. #import "KCStatusCellViewController.h" 
  10. #import "KCStatus.h" 
  11. #import "KCStatusTableViewCell.h" 
  12.  
  13. @interface KCStatusCellViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>{ 
  14.     UITableView *_tableView; 
  15.     NSMutableArray *_status; 
  16.     NSMutableArray *_statusCells;//存儲cell,用於計算高度 
  17. @end 
  18.  
  19. @implementation KCStatusCellViewController 
  20. - (void)viewDidLoad { 
  21.     [super viewDidLoad]; 
  22.      
  23.     //初始化數據 
  24.     [self initData]; 
  25.      
  26.     //創建一個分組樣式的UITableView 
  27.     _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped]; 
  28.      
  29.     //設置數據源,注意必須實現對應的UITableViewDataSource協議 
  30.     _tableView.dataSource=self; 
  31.     //設置代理 
  32.     _tableView.delegate=self; 
  33.      
  34.     [self.view addSubview:_tableView]; 
  35.  
  36. #pragma mark 加載數據 
  37. -(void)initData{ 
  38.     NSString *path=[[NSBundle mainBundle] pathForResource:@"StatusInfo" ofType:@"plist"]; 
  39.     NSArray *array=[NSArray arrayWithContentsOfFile:path]; 
  40.     _status=[[NSMutableArray alloc]init]; 
  41.     _statusCells=[[NSMutableArray alloc]init]; 
  42.     [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
  43.         [_status addObject:[KCStatus statusWithDictionary:obj]]; 
  44.         KCStatusTableViewCell *cell=[[KCStatusTableViewCell alloc]init]; 
  45.         [_statusCells addObject:cell]; 
  46.     }]; 
  47. #pragma mark - 數據源方法 
  48. #pragma mark 返回分組數 
  49. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
  50.     return 1; 
  51.  
  52. #pragma mark 返回每組行數 
  53. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
  54.  
  55.     return _status.count; 
  56.  
  57. #pragma mark返回每行的單元格 
  58. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
  59.     static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1"
  60.     KCStatusTableViewCell *cell; 
  61.     cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
  62.     if(!cell){ 
  63.         cell=[[KCStatusTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
  64.     } 
  65.     //在此設置微博,以便重新佈局 
  66.     KCStatus *status=_status[indexPath.row]; 
  67.     cell.status=status; 
  68.     return cell; 
  69.  
  70. #pragma mark - 代理方法 
  71. #pragma mark 重新設置單元格高度 
  72. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 
  73.     //KCStatusTableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath]; 
  74.     KCStatusTableViewCell *cell= _statusCells[indexPath.row]; 
  75.     cell.status=_status[indexPath.row]; 
  76.     return cell.height; 
  77.  
  78. #pragma mark 重寫狀態樣式方法 
  79. -(UIStatusBarStyle)preferredStatusBarStyle{ 
  80.     return UIStatusBarStyleLightContent; 
  81. @end 
這個類中需要重點強調一下:Cell的高度需要重新設置(前面說過無論Cell內部設置多高都沒有用,需要重新設置),這裏採用的方法是首先創建對應的Cell,然後在- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;方法中設置微博數據計算高度通知UITableView。
最後我們看一下運行的效果:
常用操作
UITableView和UITableViewCell提供了強大的操作功能,這一節中會重點討論刪除、增加、排序等操作。爲了方便演示我們還是在之前的通訊錄的基礎上演示,在此之前先來給視圖控制器添加一個工具條,在工具條左側放一個刪除按鈕,右側放一個添加按鈕:
  1. #pragma mark 添加工具欄 
  2. -(void)addToolbar{ 
  3.     CGRect frame=self.view.frame; 
  4.     _toolbar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, kContactToolbarHeight)]; 
  5.     //    _toolbar.backgroundColor=[UIColor colorWithHue:246/255.0 saturation:246/255.0 brightness:246/255.0 alpha:1]; 
  6.     [self.view addSubview:_toolbar]; 
  7.     UIBarButtonItem *removeButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(remove)]; 
  8.     UIBarButtonItem *flexibleButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; 
  9.     UIBarButtonItem *addButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add)]; 
  10.     NSArray *buttonArray=[NSArray arrayWithObjects:removeButton,flexibleButton,addButton, nil]; 
  11.     _toolbar.items=buttonArray; 
1.刪除
在UITableView中無論是刪除操作還是添加操作都是通過修改UITableView的編輯狀態來改變的(除非你不用UITableView自帶的刪除功能)。在刪除按鈕中我們設置UITableView的編輯狀態:
  1. #pragma mark 刪除 
  2. -(void)remove{ 
  3.     //直接通過下面的方法設置編輯狀態沒有動畫 
  4.     //_tableView.editing=!_tableView.isEditing; 
  5.      
  6.     [_tableView setEditing:!_tableView.isEditing animated:true]; 
點擊刪除按鈕會在Cell的左側顯示刪除按鈕:
此時點擊左側刪除圖標右側出現刪除:
用過iOS的朋友都知道,一般這種Cell如果向左滑動右側就會出現刪除按鈕直接刪除就可以了。其實實現這個功能只要實現代理-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;方法,只要實現了此方法向左滑動就會顯示刪除按鈕。只要點擊刪除按鈕這個方法就會調用,但是需要注意的是無論是刪除還是添加都是執行這個方法,只是第二個參數類型不同。下面看一下具體的刪除實現:
  1. #pragma mark 刪除操作 
  2. //實現了此方法向左滑動就會顯示刪除按鈕 
  3. -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ 
  4.     KCContactGroup *group =_contacts[indexPath.section]; 
  5.     KCContact *contact=group.contacts[indexPath.row]; 
  6.     if (editingStyle==UITableViewCellEditingStyleDelete) { 
  7.         [group.contacts removeObject:contact]; 
  8.         //考慮到性能這裏不建議使用reloadData 
  9.         //[tableView reloadData]; 
  10.         //使用下面的方法既可以局部刷新又有動畫效果 
  11.         [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom]; 
  12.          
  13.         //如果當前組中沒有數據則移除組刷新整個表格 
  14.         if (group.contacts.count==0) { 
  15.             [_contacts removeObject:group]; 
  16.             [tableView reloadData]; 
  17.         } 
  18.     } 
 
從這段代碼我們再次看到了MVC的思想,要修改UI先修改數據。而且我們看到了另一個刷新表格的方法- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;,使用這個方法可以再刪除之後刷新對應的單元格。效果如下:
2.添加
添加和刪除操作都是設置UITableView的編輯狀態,具體是添加還是刪除需要根據代理方法-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath;的返回值來確定。因此這裏我們定義一個變量來記錄點擊了哪個按鈕,根據點擊按鈕的不同在這個方法中返回不同的值。
  1. #pragma mark 取得當前操作狀態,根據不同的狀態左側出現不同的操作按鈕 
  2. -(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{ 
  3.     if (_isInsert) { 
  4.         return UITableViewCellEditingStyleInsert; 
  5.     } 
  6.     return UITableViewCellEditingStyleDelete; 
  7. #pragma mark 編輯操作(刪除或添加) 
  8. //實現了此方法向左滑動就會顯示刪除(或添加)圖標 
  9. -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ 
  10.     KCContactGroup *group =_contacts[indexPath.section]; 
  11.     KCContact *contact=group.contacts[indexPath.row]; 
  12.     if (editingStyle==UITableViewCellEditingStyleDelete) { 
  13.         [group.contacts removeObject:contact]; 
  14.         //考慮到性能這裏不建議使用reloadData 
  15.         //[tableView reloadData]; 
  16.         //使用下面的方法既可以局部刷新又有動畫效果 
  17.         [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom]; 
  18.          
  19.         //如果當前組中沒有數據則移除組刷新整個表格 
  20.         if (group.contacts.count==0) { 
  21.             [_contacts removeObject:group]; 
  22.             [tableView reloadData]; 
  23.         } 
  24.     }else if(editingStyle==UITableViewCellEditingStyleInsert){ 
  25.         KCContact *newContact=[[KCContact alloc]init]; 
  26.         newContact.firstName=@"first"
  27.         newContact.lastName=@"last"
  28.         newContact.phoneNumber=@"12345678901"
  29.         [group.contacts insertObject:newContact atIndex:indexPath.row]; 
  30.         [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];//注意這裏沒有使用reladData刷新 
  31.     } 
運行效果:
3.排序
只要實現-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath;代理方法當UITableView處於編輯狀態時就可以排序。
  1. #pragma mark 排序 
  2. //只要實現這個方法在編輯狀態右側就有排序圖標 
  3. -(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{ 
  4.     KCContactGroup *sourceGroup =_contacts[sourceIndexPath.section]; 
  5.     KCContact *sourceContact=sourceGroup.contacts[sourceIndexPath.row]; 
  6.     KCContactGroup *destinationGroup =_contacts[destinationIndexPath.section]; 
  7.      
  8.     [sourceGroup.contacts removeObject:sourceContact]; 
  9.     if(sourceGroup.contacts.count==0){ 
  10.         [_contacts removeObject:sourceGroup]; 
  11.         [tableView reloadData]; 
  12.     } 
  13.      
  14.     [destinationGroup.contacts insertObject:sourceContact atIndex:destinationIndexPath.row]; 
  15.      
運行效果:
最後給大家附上上面幾種操作的完整代碼:
  1. // 
  2. //  KCContactViewController.m 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8. #import "KCContactViewController.h" 
  9. #import "KCContact.h" 
  10. #import "KCContactGroup.h" 
  11. #define kContactToolbarHeight 44 
  12. @interface KCContactViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>{ 
  13.     UITableView *_tableView; 
  14.     UIToolbar *_toolbar; 
  15.     NSMutableArray *_contacts;//聯繫人模型 
  16.     NSIndexPath *_selectedIndexPath;//當前選中的組和行 
  17.     BOOL _isInsert;//記錄是點擊了插入還是刪除按鈕 
  18. @end 
  19. @implementation KCContactViewController 
  20. - (void)viewDidLoad { 
  21.     [super viewDidLoad]; 
  22.      
  23.     //初始化數據 
  24.     [self initData]; 
  25.      
  26.     //創建一個分組樣式的UITableView 
  27.     _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped]; 
  28.     _tableView.contentInset=UIEdgeInsetsMake(kContactToolbarHeight, 0, 0, 0); 
  29.     [self.view addSubview:_tableView]; 
  30.      
  31.     //添加工具欄 
  32.     [self addToolbar]; 
  33.      
  34.     //設置數據源,注意必須實現對應的UITableViewDataSource協議 
  35.     _tableView.dataSource=self; 
  36.     //設置代理 
  37.     _tableView.delegate=self; 
  38.      
  39.      
  40. #pragma mark 加載數據 
  41. -(void)initData{ 
  42.     _contacts=[[NSMutableArray alloc]init]; 
  43.      
  44.     KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"]; 
  45.     KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"]; 
  46.     KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]]; 
  47.     [_contacts addObject:group1]; 
  48.      
  49.      
  50.      
  51.     KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"]; 
  52.     KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"]; 
  53.     KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"]; 
  54.     KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]]; 
  55.     [_contacts addObject:group2]; 
  56.      
  57.      
  58.      
  59.     KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"]; 
  60.     KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"]; 
  61.      
  62.     KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]]; 
  63.     [_contacts addObject:group3]; 
  64.      
  65.      
  66.     KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"]; 
  67.     KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"]; 
  68.     KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"]; 
  69.     KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"]; 
  70.     KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"]; 
  71.     KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]]; 
  72.     [_contacts addObject:group4]; 
  73.      
  74.      
  75.     KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"]; 
  76.     KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"]; 
  77.     KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"]; 
  78.     KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]]; 
  79.     [_contacts addObject:group5]; 
  80.      
  81. #pragma mark 添加工具欄 
  82. -(void)addToolbar{ 
  83.     CGRect frame=self.view.frame; 
  84.     _toolbar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, kContactToolbarHeight)]; 
  85.     //    _toolbar.backgroundColor=[UIColor colorWithHue:246/255.0 saturation:246/255.0 brightness:246/255.0 alpha:1]; 
  86.     [self.view addSubview:_toolbar]; 
  87.     UIBarButtonItem *removeButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(remove)]; 
  88.     UIBarButtonItem *flexibleButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; 
  89.     UIBarButtonItem *addButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add)]; 
  90.     NSArray *buttonArray=[NSArray arrayWithObjects:removeButton,flexibleButton,addButton, nil]; 
  91.     _toolbar.items=buttonArray; 
  92. #pragma mark 刪除 
  93. -(void)remove{ 
  94.     //直接通過下面的方法設置編輯狀態沒有動畫 
  95.     //_tableView.editing=!_tableView.isEditing; 
  96.     _isInsert=false
  97.     [_tableView setEditing:!_tableView.isEditing animated:true]; 
  98. #pragma mark 添加 
  99. -(void)add{ 
  100.     _isInsert=true
  101.     [_tableView setEditing:!_tableView.isEditing animated:true]; 
  102. #pragma mark - 數據源方法 
  103. #pragma mark 返回分組數 
  104. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
  105.     return _contacts.count; 
  106. #pragma mark 返回每組行數 
  107. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
  108.     KCContactGroup *group1=_contacts[section]; 
  109.     return group1.contacts.count; 
  110. #pragma mark返回每行的單元格 
  111. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
  112.     //NSIndexPath是一個對象,記錄了組和行信息 
  113.     KCContactGroup *group=_contacts[indexPath.section]; 
  114.     KCContact *contact=group.contacts[indexPath.row]; 
  115.     static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1"
  116.     //首先根據標識去緩存池取 
  117.     UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
  118.     //如果緩存池沒有取到則重新創建並放到緩存池中 
  119.     if(!cell){ 
  120.         cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier]; 
  121.     } 
  122.      
  123.     cell.textLabel.text=[contact getName]; 
  124.     cell.detailTextLabel.text=contact.phoneNumber; 
  125.      
  126.     return cell; 
  127. #pragma mark - 代理方法 
  128. #pragma mark 設置分組標題 
  129. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ 
  130.     KCContactGroup *group=_contacts[section]; 
  131.     return group.name; 
  132. #pragma mark 編輯操作(刪除或添加) 
  133. //實現了此方法向左滑動就會顯示刪除(或添加)圖標 
  134. -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ 
  135.     KCContactGroup *group =_contacts[indexPath.section]; 
  136.     KCContact *contact=group.contacts[indexPath.row]; 
  137.     if (editingStyle==UITableViewCellEditingStyleDelete) { 
  138.         [group.contacts removeObject:contact]; 
  139.         //考慮到性能這裏不建議使用reloadData 
  140.         //[tableView reloadData]; 
  141.         //使用下面的方法既可以局部刷新又有動畫效果 
  142.         [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom]; 
  143.          
  144.         //如果當前組中沒有數據則移除組刷新整個表格 
  145.         if (group.contacts.count==0) { 
  146.             [_contacts removeObject:group]; 
  147.             [tableView reloadData]; 
  148.         } 
  149.     }else if(editingStyle==UITableViewCellEditingStyleInsert){ 
  150.         KCContact *newContact=[[KCContact alloc]init]; 
  151.         newContact.firstName=@"first"
  152.         newContact.lastName=@"last"
  153.         newContact.phoneNumber=@"12345678901"
  154.         [group.contacts insertObject:newContact atIndex:indexPath.row]; 
  155.         [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];//注意這裏沒有使用reladData刷新 
  156.     } 
  157. #pragma mark 排序 
  158. //只要實現這個方法在編輯狀態右側就有排序圖標 
  159. -(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{ 
  160.     KCContactGroup *sourceGroup =_contacts[sourceIndexPath.section]; 
  161.     KCContact *sourceContact=sourceGroup.contacts[sourceIndexPath.row]; 
  162.     KCContactGroup *destinationGroup =_contacts[destinationIndexPath.section]; 
  163.      
  164.     [sourceGroup.contacts removeObject:sourceContact]; 
  165.     [destinationGroup.contacts insertObject:sourceContact atIndex:destinationIndexPath.row]; 
  166.     if(sourceGroup.contacts.count==0){ 
  167.         [_contacts removeObject:sourceGroup]; 
  168.         [tableView reloadData]; 
  169.     } 
  170. #pragma mark 取得當前操作狀態,根據不同的狀態左側出現不同的操作按鈕 
  171. -(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{ 
  172.     if (_isInsert) { 
  173.         return UITableViewCellEditingStyleInsert; 
  174.     } 
  175.     return UITableViewCellEditingStyleDelete; 
  176. #pragma mark 重寫狀態樣式方法 
  177. -(UIStatusBarStyle)preferredStatusBarStyle{ 
  178.     return UIStatusBarStyleLightContent; 
  179. @end 
通過前面的演示這裏簡單總結一些UITableView的刷新方法:
- (void)reloadData;刷新整個表格。
- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation NS_AVAILABLE_IOS(3_0);刷新指定的分組和行。
- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation NS_AVAILABLE_IOS(3_0);刷新指定的分組。
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;刪除時刷新指定的行數據。
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;添加時刷新指定的行數據。
 
UITableViewController
很多時候一個UIViewController中只有一個UITableView,因此蘋果官方爲了方便大家開發直接提供了一個UITableViewController,這個控制器 UITableViewController實現了UITableView數據源和代理協議,內部定義了一個tableView屬性供外部訪問,同時自動鋪滿整個屏幕、自動伸縮以方便我們的開發。當然UITableViewController也並不是簡單的幫我們定義完UITableView並且設置了數據源、代理而已,它還有其他強大的功能,例如刷新控件、滾動過程中固定分組標題等。
 
有時候一個表格中的數據特別多,檢索起來就顯得麻煩,這個時候可以實現一個搜索功能幫助用戶查找數據,其實搜索的原理很簡單:修改模型、刷新表格。下面使用UITableViewController簡單演示一下這個功能:
  1. // 
  2. //  KCContactTableViewController.m 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8. #import "KCContactTableViewController.h" 
  9. #import "KCContact.h" 
  10. #import "KCContactGroup.h" 
  11. #define kSearchbarHeight 44 
  12. @interface KCContactTableViewController ()<UISearchBarDelegate>{ 
  13.     UITableView *_tableView; 
  14.     UISearchBar *_searchBar; 
  15.     //UISearchDisplayController *_searchDisplayController; 
  16.     NSMutableArray *_contacts;//聯繫人模型 
  17.     NSMutableArray *_searchContacts;//符合條件的搜索聯繫人 
  18.     BOOL _isSearching; 
  19. @end 
  20. @implementation KCContactTableViewController 
  21. - (void)viewDidLoad { 
  22.     [super viewDidLoad]; 
  23.     //初始化數據 
  24.     [self initData]; 
  25.      
  26.     //添加搜索框 
  27.     [self addSearchBar]; 
  28. #pragma mark - 數據源方法 
  29. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
  30.     if (_isSearching) { 
  31.         return 1; 
  32.     } 
  33.     return _contacts.count;; 
  34. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
  35.     if (_isSearching) { 
  36.         return _searchContacts.count; 
  37.     } 
  38.     KCContactGroup *group1=_contacts[section]; 
  39.     return group1.contacts.count; 
  40. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
  41.     KCContact *contact=nil; 
  42.      
  43.     if (_isSearching) { 
  44.         contact=_searchContacts[indexPath.row]; 
  45.     }else
  46.         KCContactGroup *group=_contacts[indexPath.section]; 
  47.         contact=group.contacts[indexPath.row]; 
  48.     } 
  49.      
  50.     static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1"
  51.      
  52.     //首先根據標識去緩存池取 
  53.     UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
  54.     //如果緩存池沒有取到則重新創建並放到緩存池中 
  55.     if(!cell){ 
  56.         cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier]; 
  57.     } 
  58.      
  59.     cell.textLabel.text=[contact getName]; 
  60.     cell.detailTextLabel.text=contact.phoneNumber; 
  61.      
  62.     return cell; 
  63. #pragma mark - 代理方法 
  64. #pragma mark 設置分組標題 
  65. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ 
  66.     KCContactGroup *group=_contacts[section]; 
  67.     return group.name; 
  68. #pragma mark - 搜索框代理 
  69. #pragma mark  取消搜索 
  70. -(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{ 
  71.     _isSearching=NO; 
  72.     _searchBar.text=@""
  73.     [self.tableView reloadData]; 
  74. #pragma mark 輸入搜索關鍵字 
  75. -(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ 
  76.     if([_searchBar.text isEqual:@""]){ 
  77.         _isSearching=NO; 
  78.         [self.tableView reloadData]; 
  79.         return
  80.     } 
  81.     [self searchDataWithKeyWord:_searchBar.text]; 
  82. #pragma mark 點擊虛擬鍵盤上的搜索時 
  83. -(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ 
  84.      
  85.     [self searchDataWithKeyWord:_searchBar.text]; 
  86.      
  87.     [_searchBar resignFirstResponder];//放棄第一響應者對象,關閉虛擬鍵盤 
  88. #pragma mark 重寫狀態樣式方法 
  89. -(UIStatusBarStyle)preferredStatusBarStyle{ 
  90.     return UIStatusBarStyleLightContent; 
  91. #pragma mark 加載數據 
  92. -(void)initData{ 
  93.     _contacts=[[NSMutableArray alloc]init]; 
  94.      
  95.     KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"]; 
  96.     KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"]; 
  97.     KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]]; 
  98.     [_contacts addObject:group1]; 
  99.      
  100.      
  101.      
  102.     KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"]; 
  103.     KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"]; 
  104.     KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"]; 
  105.     KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]]; 
  106.     [_contacts addObject:group2]; 
  107.      
  108.      
  109.      
  110.     KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"]; 
  111.     KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"]; 
  112.      
  113.     KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]]; 
  114.     [_contacts addObject:group3]; 
  115.      
  116.      
  117.     KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"]; 
  118.     KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"]; 
  119.     KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"]; 
  120.     KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"]; 
  121.     KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"]; 
  122.     KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]]; 
  123.     [_contacts addObject:group4]; 
  124.      
  125.      
  126.     KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"]; 
  127.     KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"]; 
  128.     KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"]; 
  129.     KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]]; 
  130.     [_contacts addObject:group5]; 
  131.      
  132. #pragma mark 搜索形成新數據 
  133. -(void)searchDataWithKeyWord:(NSString *)keyWord{ 
  134.     _isSearching=YES; 
  135.     _searchContacts=[NSMutableArray array]; 
  136.     [_contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
  137.         KCContactGroup *group=obj; 
  138.         [group.contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
  139.             KCContact *contact=obj; 
  140.             if ([contact.firstName.uppercaseString containsString:keyWord.uppercaseString]||[contact.lastName.uppercaseString containsString:keyWord.uppercaseString]||[contact.phoneNumber containsString:keyWord]) { 
  141.                 [_searchContacts addObject:contact]; 
  142.             } 
  143.         }]; 
  144.     }]; 
  145.      
  146.     //刷新表格 
  147.     [self.tableView reloadData]; 
  148. #pragma mark 添加搜索欄 
  149. -(void)addSearchBar{ 
  150.     CGRect searchBarRect=CGRectMake(0, 0, self.view.frame.size.width, kSearchbarHeight); 
  151.     _searchBar=[[UISearchBar alloc]initWithFrame:searchBarRect]; 
  152.     _searchBar.placeholder=@"Please input key word..."
  153.     //_searchBar.keyboardType=UIKeyboardTypeAlphabet;//鍵盤類型 
  154.     //_searchBar.autocorrectionType=UITextAutocorrectionTypeNo;//自動糾錯類型 
  155.     //_searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone;//哪一次shitf被自動按下 
  156.     _searchBar.showsCancelButton=YES;//顯示取消按鈕 
  157.     //添加搜索框到頁眉位置 
  158.     _searchBar.delegate=self; 
  159.     self.tableView.tableHeaderView=_searchBar; 
  160. @end 
運行效果:
在上面的搜索中除了使用一個_contacts變量去保存聯繫人數據還專門定義了一個_searchContact變量用於保存搜索的結果。在輸入搜索關鍵字時我們刷新了表格,此時會調用表格的數據源方法,在這個方法中我們根據定義的搜索狀態去決定顯示原始數據還是搜索結果。
 
我們發現每次搜索完後都需要手動刷新表格來顯示搜索結果,而且當沒有搜索關鍵字的時候還需要將當前的tableView重新設置爲初始狀態。也就是這個過程中我們要用一個tableView顯示兩種狀態的不同數據,自然會提高程序邏輯複雜度。爲了簡化這個過程,我們可以使用UISearchDisplayController,UISearchDisplayController內部也有一個UITableView類型的對象searchResultsTableView,如果我們設置它的數據源代理爲當前控制器,那麼它完全可以像UITableView一樣加載數據。同時它本身也有搜索監聽的方法,我們不必在監聽UISearchBar輸入內容,直接使用它的方法即可自動刷新其內部表格。爲了和前面的方法對比在下面的代碼中沒有直接刪除原來的方式而是註釋了對應代碼大家可以對照學習:
  1. // 
  2. //  KCContactTableViewController.m 
  3. //  UITableView 
  4. // 
  5. //  Created by Kenshin Cui on 14-3-1. 
  6. //  Copyright (c) 2014年 Kenshin Cui. All rights reserved. 
  7. // 
  8. #import "KCContactTableViewControllerWithUISearchDisplayController.h" 
  9. #import "KCContact.h" 
  10. #import "KCContactGroup.h" 
  11. #define kSearchbarHeight 44 
  12. @interface KCContactTableViewControllerWithUISearchDisplayController ()<UISearchBarDelegate,UISearchDisplayDelegate>{ 
  13.     UITableView *_tableView; 
  14.     UISearchBar *_searchBar; 
  15.     UISearchDisplayController *_searchDisplayController; 
  16.     NSMutableArray *_contacts;//聯繫人模型 
  17.     NSMutableArray *_searchContacts;//符合條件的搜索聯繫人 
  18.     //BOOL _isSearching; 
  19. @end 
  20. @implementation KCContactTableViewControllerWithUISearchDisplayController 
  21. - (void)viewDidLoad { 
  22.     [super viewDidLoad]; 
  23.     //初始化數據 
  24.     [self initData]; 
  25.      
  26.     //添加搜索框 
  27.     [self addSearchBar]; 
  28. #pragma mark - 數據源方法 
  29. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
  30. //    if (_isSearching) { 
  31. //        return 1; 
  32. //    } 
  33.     //如果當前是UISearchDisplayController內部的tableView則不分組 
  34.     if (tableView==self.searchDisplayController.searchResultsTableView) { 
  35.         return 1; 
  36.     } 
  37.     return _contacts.count;; 
  38. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
  39. //    if (_isSearching) { 
  40. //        return _searchContacts.count; 
  41. //    } 
  42.     //如果當前是UISearchDisplayController內部的tableView則使用搜索數據 
  43.     if (tableView==self.searchDisplayController.searchResultsTableView) { 
  44.         return _searchContacts.count; 
  45.     } 
  46.     KCContactGroup *group1=_contacts[section]; 
  47.     return group1.contacts.count; 
  48. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
  49.     KCContact *contact=nil; 
  50.      
  51. //    if (_isSearching) { 
  52. //        contact=_searchContacts[indexPath.row]; 
  53. //    }else{ 
  54. //        KCContactGroup *group=_contacts[indexPath.section]; 
  55. //        contact=group.contacts[indexPath.row]; 
  56. //    } 
  57.     //如果當前是UISearchDisplayController內部的tableView則使用搜索數據 
  58.     if (tableView==self.searchDisplayController.searchResultsTableView) { 
  59.         contact=_searchContacts[indexPath.row]; 
  60.     }else
  61.         KCContactGroup *group=_contacts[indexPath.section]; 
  62.         contact=group.contacts[indexPath.row]; 
  63.     } 
  64.      
  65.     static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1"
  66.      
  67.     //首先根據標識去緩存池取 
  68.     UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
  69.     //如果緩存池沒有取到則重新創建並放到緩存池中 
  70.     if(!cell){ 
  71.         cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier]; 
  72.     } 
  73.      
  74.     cell.textLabel.text=[contact getName]; 
  75.     cell.detailTextLabel.text=contact.phoneNumber; 
  76.      
  77.     return cell; 
  78. #pragma mark - 代理方法 
  79. #pragma mark 設置分組標題 
  80. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ 
  81.     if (tableView==self.searchDisplayController.searchResultsTableView) { 
  82.         return @"搜索結果"
  83.     } 
  84.     KCContactGroup *group=_contacts[section]; 
  85.     return group.name; 
  86. #pragma mark 選中之前 
  87. -(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
  88.     [_searchBar resignFirstResponder];//退出鍵盤 
  89.     return indexPath; 
  90. #pragma mark - 搜索框代理 
  91. //#pragma mark  取消搜索 
  92. //-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{ 
  93. //    //_isSearching=NO; 
  94. //    _searchBar.text=@""; 
  95. //    //[self.tableView reloadData]; 
  96. //    [_searchBar resignFirstResponder]; 
  97. //} 
  98. // 
  99. //#pragma mark 輸入搜索關鍵字 
  100. //-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ 
  101. //    if([_searchBar.text isEqual:@""]){ 
  102. //        //_isSearching=NO; 
  103. //        //[self.tableView reloadData]; 
  104. //        return; 
  105. //    } 
  106. //    [self searchDataWithKeyWord:_searchBar.text]; 
  107. //} 
  108. //#pragma mark 點擊虛擬鍵盤上的搜索時 
  109. //-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ 
  110. //     
  111. //    [self searchDataWithKeyWord:_searchBar.text]; 
  112. //     
  113. //    [_searchBar resignFirstResponder];//放棄第一響應者對象,關閉虛擬鍵盤 
  114. //} 
  115. #pragma mark - UISearchDisplayController代理方法 
  116. -(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{ 
  117.     [self searchDataWithKeyWord:searchString]; 
  118.     return YES; 
  119. #pragma mark 重寫狀態樣式方法 
  120. -(UIStatusBarStyle)preferredStatusBarStyle{ 
  121.     return UIStatusBarStyleLightContent; 
  122. #pragma mark 加載數據 
  123. -(void)initData{ 
  124.     _contacts=[[NSMutableArray alloc]init]; 
  125.      
  126.     KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"]; 
  127.     KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"]; 
  128.     KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]]; 
  129.     [_contacts addObject:group1]; 
  130.      
  131.      
  132.      
  133.     KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"]; 
  134.     KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"]; 
  135.     KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"]; 
  136.     KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]]; 
  137.     [_contacts addObject:group2]; 
  138.      
  139.      
  140.      
  141.     KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"]; 
  142.     KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"]; 
  143.      
  144.     KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]]; 
  145.     [_contacts addObject:group3]; 
  146.      
  147.      
  148.     KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"]; 
  149.     KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"]; 
  150.     KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"]; 
  151.     KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"]; 
  152.     KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"]; 
  153.     KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]]; 
  154.     [_contacts addObject:group4]; 
  155.      
  156.      
  157.     KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"]; 
  158.     KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"]; 
  159.     KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"]; 
  160.     KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]]; 
  161.     [_contacts addObject:group5]; 
  162.      
  163. #pragma mark 搜索形成新數據 
  164. -(void)searchDataWithKeyWord:(NSString *)keyWord{ 
  165.     //_isSearching=YES; 
  166.     _searchContacts=[NSMutableArray array]; 
  167.     [_contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
  168.         KCContactGroup *group=obj; 
  169.         [group.contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
  170.             KCContact *contact=obj; 
  171.             if ([contact.firstName.uppercaseString containsString:keyWord.uppercaseString]||[contact.lastName.uppercaseString containsString:keyWord.uppercaseString]||[contact.phoneNumber containsString:keyWord]) { 
  172.                 [_searchContacts addObject:contact]; 
  173.             } 
  174.         }]; 
  175.     }]; 
  176.      
  177.     //刷新表格 
  178.     //[self.tableView reloadData]; 
  179. #pragma mark 添加搜索欄 
  180. -(void)addSearchBar{ 
  181.     _searchBar=[[UISearchBar alloc]init]; 
  182.     [_searchBar sizeToFit];//大小自適應容器 
  183.     _searchBar.placeholder=@"Please input key word..."
  184.     _searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone; 
  185.     _searchBar.showsCancelButton=YES;//顯示取消按鈕 
  186.     //添加搜索框到頁眉位置 
  187.     _searchBar.delegate=self; 
  188.     self.tableView.tableHeaderView=_searchBar; 
  189.     _searchDisplayController=[[UISearchDisplayController alloc]initWithSearchBar:_searchBar contentsController:self]; 
  190.     _searchDisplayController.delegate=self; 
  191.     _searchDisplayController.searchResultsDataSource=self; 
  192.     _searchDisplayController.searchResultsDelegate=self; 
  193.     [_searchDisplayController setActive:NO animated:YES]; 
  194. @end 
運行效果:
注意:如果使用Storyboard或xib方式創建上述代碼則無需定義UISearchDisplayController成員變量,因爲每個UIViewController中已經有一個searchDisplayController對象。
 
MVC模式
通過UITableView的學習相信大家對於iOS的MVC已經有一個大致的瞭解,這裏簡單的分析一下iOS中MVC模式的設計方式。在iOS中多數數據源視圖控件(View)都有一個dataSource屬性用於和控制器(Controller)交互,而數據來源我們一般會以數據模型(Model)的形式進行定義,View不直接和模型交互,而是通過Controller間接讀取數據。
 
就拿前面的聯繫人應用舉例,UITableView作爲視圖(View)並不能直接訪問模型Contact,它要顯示聯繫人信息只能通過控制器(Controller)來提供數據源方法。同樣的控制器本身就擁有視圖控件,可以操作視圖,也就是說視圖和控制器之間可以互相訪問。而模型既不能訪問視圖也不能訪問控制器。具體依賴關係如下圖:

 

發佈了41 篇原創文章 · 獲贊 5 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章