UITableView全面解析

时间:2021-12-14 20:26:38

本文转自:http://www.cocoachina.com/ios/20140922/9710.html

在iOS开发中UITableView可以说是使用最广泛的控件,我们平时使用的软件中到处都可以看到它的影子,类似于微信、QQ、新浪微博等软件基本上随处都是UITableView。当然它的广泛使用自然离不开它强大的功能,今天这篇文章将针对UITableView重点展开讨论。今天的主要内容包括:

1.基本介绍
2.数据源
3.代理
4.性能优化
5.UITableViewCell
6.常用操作
7.UITableViewController
8.MVC模式
 
基本介绍
UITableView有两种风格:UITableViewStylePlain和UITableViewStyleGrouped。这两者操作起来其实并没有本质区别,只是后者按分组样式显示前者按照普通样式显示而已。大家先看一下两者的应用:
1>分组样式
UITableView全面解析
2>不分组样式
UITableView全面解析
大家可以看到在UITableView中数据只有行的概念,并没有列的概念,因为在手机操作系统中显示多列是不利于操作的。UITableView中每行数据都是一个UITableViewCell,在这个控件中为了显示更多的信息,iOS已经在其内部设置好了多个子控件以供开发者使用。如果我们查看UITableViewCell的声明文件可以发现在内部有一个UIView控件(contentView,作为其他元素的父控件)、两个UILable控件(textLabel、detailTextLabel)、一个UIImage控件(imageView),分别用于容器、显示内容、详情和图片。使用效果类似于微信、QQ信息列表:
UITableView全面解析
当然,这些子控件并不一定要全部使用,具体操作时可以通过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. #import
  9. @interface KCContact : NSObject
  10. #pragma mark 姓
  11. @property (nonatomic,copy) NSString *firstName;
  12. #pragma mark 名
  13. @property (nonatomic,copy) NSString *lastName;
  14. #pragma mark 手机号码
  15. @property (nonatomic,copy) NSString *phoneNumber;
  16. #pragma mark 带参数的构造函数
  17. -(KCContact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber;
  18. #pragma mark 取得姓名
  19. -(NSString *)getName;
  20. #pragma mark 带参数的静态对象初始化方法
  21. +(KCContact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber;
  22. @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. #import "KCContact.h"
  9. @implementation KCContact
  10. -(KCContact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber{
  11. if(self=[super init]){
  12. self.firstName=firstName;
  13. self.lastName=lastName;
  14. self.phoneNumber=phoneNumber;
  15. }
  16. return self;
  17. }
  18. -(NSString *)getName{
  19. return [NSString stringWithFormat:@"%@ %@",_lastName,_firstName];
  20. }
  21. +(KCContact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber{
  22. KCContact *contact1=[[KCContact alloc]initWithFirstName:firstName andLastName:lastName andPhoneNumber:phoneNumber];
  23. return contact1;
  24. }
  25. @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. #import
  9. #import "KCContact.h"
  10. @interface KCContactGroup : NSObject
  11. #pragma mark 组名
  12. @property (nonatomic,copy) NSString *name;
  13. #pragma mark 分组描述
  14. @property (nonatomic,copy) NSString *detail;
  15. #pragma mark 联系人
  16. @property (nonatomic,strong) NSMutableArray *contacts;
  17. #pragma mark 带参数个构造函数
  18. -(KCContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts;
  19. #pragma mark 静态初始化方法
  20. +(KCContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts;
  21. @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. #import "KCContactGroup.h"
  9. @implementation KCContactGroup
  10. -(KCContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts{
  11. if (self=[super init]) {
  12. self.name=name;
  13. self.detail=detail;
  14. self.contacts=contacts;
  15. }
  16. return self;
  17. }
  18. +(KCContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts{
  19. KCContactGroup *group1=[[KCContactGroup alloc]initWithName:name andDetail:detail andContacts:contacts];
  20. return group1;
  21. }
  22. @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. #import "KCMainViewController.h"
  9. #import "KCContact.h"
  10. #import "KCContactGroup.h"
  11. @interface KCMainViewController (){
  12. UITableView *_tableView;
  13. NSMutableArray *_contacts;//联系人模型
  14. }
  15. @end
  16. @implementation KCMainViewController
  17. - (void)viewDidLoad {
  18. [super viewDidLoad];
  19. //初始化数据
  20. [self initData];
  21. //创建一个分组样式的UITableView
  22. _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
  23. //设置数据源,注意必须实现对应的UITableViewDataSource协议
  24. _tableView.dataSource=self;
  25. [self.view addSubview:_tableView];
  26. }
  27. #pragma mark 加载数据
  28. -(void)initData{
  29. _contacts=[[NSMutableArray alloc]init];
  30. KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"];
  31. KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"];
  32. KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]];
  33. [_contacts addObject:group1];
  34. KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"];
  35. KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"];
  36. KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"];
  37. KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]];
  38. [_contacts addObject:group2];
  39. KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"];
  40. KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"];
  41. KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]];
  42. [_contacts addObject:group3];
  43. KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"];
  44. KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"];
  45. KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"];
  46. KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"];
  47. KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"];
  48. KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]];
  49. [_contacts addObject:group4];
  50. KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"];
  51. KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"];
  52. KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"];
  53. KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]];
  54. [_contacts addObject:group5];
  55. }
  56. #pragma mark - 数据源方法
  57. #pragma mark 返回分组数
  58. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  59. NSLog(@"计算分组数");
  60. return _contacts.count;
  61. }
  62. #pragma mark 返回每组行数
  63. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  64. NSLog(@"计算每组(组%i)行数",section);
  65. KCContactGroup *group1=_contacts[section];
  66. return group1.contacts.count;
  67. }
  68. #pragma mark返回每行的单元格
  69. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  70. //NSIndexPath是一个结构体,记录了组和行信息
  71. NSLog(@"生成单元格(组:%i,行%i)",indexPath.section,indexPath.row);
  72. KCContactGroup *group=_contacts[indexPath.section];
  73. KCContact *contact=group.contacts[indexPath.row];
  74. UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
  75. cell.textLabel.text=[contact getName];
  76. cell.detailTextLabel.text=contact.phoneNumber;
  77. return cell;
  78. }
  79. #pragma mark 返回每组头标题名称
  80. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
  81. NSLog(@"生成组(组%i)名称",section);
  82. KCContactGroup *group=_contacts[section];
  83. return group.name;
  84. }
  85. #pragma mark 返回每组尾部说明
  86. -(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
  87. NSLog(@"生成尾部(组%i)详情",section);
  88. KCContactGroup *group=_contacts[section];
  89. return group.detail;
  90. }
  91. @end
运行可以看到如下效果:
UITableView全面解析
大家在使用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;
  9. }
效果如下:
UITableView全面解析
需要注意的是上面几个重点方法的执行顺序,请看下图:
UITableView全面解析
值得指出的是生成单元格的方法并不是一次全部调用,而是只会生产当前显示在界面上的单元格,当用户滚动操作时再显示其他单元格。
注意:随着我们的应用越来越复杂,可能经常需要调试程序,在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;
  16. }
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. #import "KCMainViewController.h"
  9. #import "KCContact.h"
  10. #import "KCContactGroup.h"
  11. @interface KCMainViewController ()<uitableviewdatasource,uitableviewdelegate,uialertviewdelegate>{
  12. UITableView *_tableView;
  13. NSMutableArray *_contacts;//联系人模型
  14. NSIndexPath *_selectedIndexPath;//当前选中的组和行
  15. }
  16. @end
  17. @implementation KCMainViewController
  18. - (void)viewDidLoad {
  19. [super viewDidLoad];
  20. //初始化数据
  21. [self initData];
  22. //创建一个分组样式的UITableView
  23. _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
  24. //设置数据源,注意必须实现对应的UITableViewDataSource协议
  25. _tableView.dataSource=self;
  26. //设置代理
  27. _tableView.delegate=self;
  28. [self.view addSubview:_tableView];
  29. }
  30. #pragma mark 加载数据
  31. -(void)initData{
  32. _contacts=[[NSMutableArray alloc]init];
  33. KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"];
  34. KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"];
  35. KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]];
  36. [_contacts addObject:group1];
  37. KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"];
  38. KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"];
  39. KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"];
  40. KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]];
  41. [_contacts addObject:group2];
  42. KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"];
  43. KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"];
  44. KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]];
  45. [_contacts addObject:group3];
  46. KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"];
  47. KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"];
  48. KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"];
  49. KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"];
  50. KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"];
  51. KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]];
  52. [_contacts addObject:group4];
  53. KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"];
  54. KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"];
  55. KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"];
  56. KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]];
  57. [_contacts addObject:group5];
  58. }
  59. #pragma mark - 数据源方法
  60. #pragma mark 返回分组数
  61. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  62. NSLog(@"计算分组数");
  63. return _contacts.count;
  64. }
  65. #pragma mark 返回每组行数
  66. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  67. NSLog(@"计算每组(组%i)行数",section);
  68. KCContactGroup *group1=_contacts[section];
  69. return group1.contacts.count;
  70. }
  71. #pragma mark返回每行的单元格
  72. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  73. //NSIndexPath是一个对象,记录了组和行信息
  74. NSLog(@"生成单元格(组:%i,行%i)",indexPath.section,indexPath.row);
  75. KCContactGroup *group=_contacts[indexPath.section];
  76. KCContact *contact=group.contacts[indexPath.row];
  77. UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
  78. cell.textLabel.text=[contact getName];
  79. cell.detailTextLabel.text=contact.phoneNumber;
  80. return cell;
  81. }
  82. #pragma mark 返回每组头标题名称
  83. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
  84. NSLog(@"生成组(组%i)名称",section);
  85. KCContactGroup *group=_contacts[section];
  86. return group.name;
  87. }
  88. #pragma mark 返回每组尾部说明
  89. -(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
  90. NSLog(@"生成尾部(组%i)详情",section);
  91. KCContactGroup *group=_contacts[section];
  92. return group.detail;
  93. }
  94. #pragma mark 返回每组标题索引
  95. -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
  96. NSLog(@"生成组索引");
  97. NSMutableArray *indexs=[[NSMutableArray alloc]init];
  98. for(KCContactGroup *group in _contacts){
  99. [indexs addObject:group.name];
  100. }
  101. return indexs;
  102. }
  103. #pragma mark - 代理方法
  104. #pragma mark 设置分组标题内容高度
  105. -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
  106. if(section==0){
  107. return 50;
  108. }
  109. return 40;
  110. }
  111. #pragma mark 设置每行高度(每行高度可以不一样)
  112. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  113. return 45;
  114. }
  115. #pragma mark 设置尾部说明内容高度
  116. -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
  117. return 40;
  118. }
  119. #pragma mark 点击行
  120. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  121. _selectedIndexPath=indexPath;
  122. KCContactGroup *group=_contacts[indexPath.section];
  123. KCContact *contact=group.contacts[indexPath.row];
  124. //创建弹出窗口
  125. UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"System Info" message:[contact getName] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
  126. alert.alertViewStyle=UIAlertViewStylePlainTextInput; //设置窗口内容样式
  127. UITextField *textField= [alert textFieldAtIndex:0]; //取得文本框
  128. textField.text=contact.phoneNumber; //设置文本框内容
  129. [alert show]; //显示窗口
  130. }
  131. #pragma mark 窗口的代理方法,用户保存数据
  132. -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
  133. //当点击了第二个按钮(OK)
  134. if (buttonIndex==1) {
  135. UITextField *textField= [alertView textFieldAtIndex:0];
  136. //修改模型数据
  137. KCContactGroup *group=_contacts[_selectedIndexPath.section];
  138. KCContact *contact=group.contacts[_selectedIndexPath.row];
  139. contact.phoneNumber=textField.text;
  140. //刷新表格
  141. [_tableView reloadData];
  142. }
  143. }
  144. #pragma mark 重写状态样式方法
  145. -(UIStatusBarStyle)preferredStatusBarStyle{
  146. return UIStatusBarStyleLightContent;
  147. }
  148. @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. }
  14. }
性能优化
前面已经说过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属性可以对其样式进行控制。其结构如下:
UITableView全面解析
有时候我们会发现很多UITableViewCell右侧可以显示不同的图标,在iOS中称之为访问器,点击可以触发不同的事件,例如设置功能:
UITableView全面解析
要设置这些图标只需要设置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. };
例如在最近通话中我们通常设置为详情图标,点击可以查看联系人详情:
UITableView全面解析
很明显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. #import "KCMainViewController.h"
  9. #import "KCContact.h"
  10. #import "KCContactGroup.h"
  11. @interface KCMainViewController ()<uitableviewdatasource,uitableviewdelegate,uialertviewdelegate>{
  12. UITableView *_tableView;
  13. NSMutableArray *_contacts;//联系人模型
  14. NSIndexPath *_selectedIndexPath;//当前选中的组和行
  15. }
  16. @end
  17. @implementation KCMainViewController
  18. - (void)viewDidLoad {
  19. [super viewDidLoad];
  20. //初始化数据
  21. [self initData];
  22. //创建一个分组样式的UITableView
  23. _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
  24. //设置数据源,注意必须实现对应的UITableViewDataSource协议
  25. _tableView.dataSource=self;
  26. //设置代理
  27. _tableView.delegate=self;
  28. [self.view addSubview:_tableView];
  29. }
  30. #pragma mark 加载数据
  31. -(void)initData{
  32. _contacts=[[NSMutableArray alloc]init];
  33. KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"];
  34. KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"];
  35. KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]];
  36. [_contacts addObject:group1];
  37. KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"];
  38. KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"];
  39. KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"];
  40. KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]];
  41. [_contacts addObject:group2];
  42. KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"];
  43. KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"];
  44. KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]];
  45. [_contacts addObject:group3];
  46. KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"];
  47. KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"];
  48. KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"];
  49. KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"];
  50. KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"];
  51. KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]];
  52. [_contacts addObject:group4];
  53. KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"];
  54. KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"];
  55. KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"];
  56. KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]];
  57. [_contacts addObject:group5];
  58. }
  59. #pragma mark - 数据源方法
  60. #pragma mark 返回分组数
  61. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  62. NSLog(@"计算分组数");
  63. return _contacts.count;
  64. }
  65. #pragma mark 返回每组行数
  66. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  67. NSLog(@"计算每组(组%i)行数",section);
  68. KCContactGroup *group1=_contacts[section];
  69. return group1.contacts.count;
  70. }
  71. #pragma mark返回每行的单元格
  72. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  73. //NSIndexPath是一个对象,记录了组和行信息
  74. NSLog(@"生成单元格(组:%i,行%i)",indexPath.section,indexPath.row);
  75. KCContactGroup *group=_contacts[indexPath.section];
  76. KCContact *contact=group.contacts[indexPath.row];
  77. //由于此方法调用十分频繁,cell的标示声明成静态变量有利于性能优化
  78. static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1";
  79. static NSString *cellIdentifierForFirstRow=@"UITableViewCellIdentifierKeyWithSwitch";
  80. //首先根据标示去缓存池取
  81. UITableViewCell *cell;
  82. if (indexPath.row==0) {
  83. cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifierForFirstRow];
  84. }else{
  85. cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  86. }
  87. //如果缓存池没有取到则重新创建并放到缓存池中
  88. if(!cell){
  89. if (indexPath.row==0) {
  90. cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifierForFirstRow];
  91. UISwitch *sw=[[UISwitch alloc]init];
  92. [sw addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventValueChanged];
  93. cell.accessoryView=sw;
  94. }else{
  95. cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
  96. cell.accessoryType=UITableViewCellAccessoryDetailButton;
  97. }
  98. }
  99. if(indexPath.row==0){
  100. ((UISwitch *)cell.accessoryView).tag=indexPath.section;
  101. }
  102. cell.textLabel.text=[contact getName];
  103. cell.detailTextLabel.text=contact.phoneNumber;
  104. NSLog(@"cell:%@",cell);
  105. return cell;
  106. }
  107. #pragma mark 返回每组头标题名称
  108. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
  109. NSLog(@"生成组(组%i)名称",section);
  110. KCContactGroup *group=_contacts[section];
  111. return group.name;
  112. }
  113. #pragma mark 返回每组尾部说明
  114. -(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
  115. NSLog(@"生成尾部(组%i)详情",section);
  116. KCContactGroup *group=_contacts[section];
  117. return group.detail;
  118. }
  119. #pragma mark 返回每组标题索引
  120. -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
  121. NSLog(@"生成组索引");
  122. NSMutableArray *indexs=[[NSMutableArray alloc]init];
  123. for(KCContactGroup *group in _contacts){
  124. [indexs addObject:group.name];
  125. }
  126. return indexs;
  127. }
  128. #pragma mark - 代理方法
  129. #pragma mark 设置分组标题内容高度
  130. -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
  131. if(section==0){
  132. return 50;
  133. }
  134. return 40;
  135. }
  136. #pragma mark 设置每行高度(每行高度可以不一样)
  137. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  138. return 45;
  139. }
  140. #pragma mark 设置尾部说明内容高度
  141. -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
  142. return 40;
  143. }
  144. #pragma mark 点击行
  145. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  146. _selectedIndexPath=indexPath;
  147. KCContactGroup *group=_contacts[indexPath.section];
  148. KCContact *contact=group.contacts[indexPath.row];
  149. //创建弹出窗口
  150. UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"System Info" message:[contact getName] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
  151. alert.alertViewStyle=UIAlertViewStylePlainTextInput; //设置窗口内容样式
  152. UITextField *textField= [alert textFieldAtIndex:0]; //取得文本框
  153. textField.text=contact.phoneNumber; //设置文本框内容
  154. [alert show]; //显示窗口
  155. }
  156. #pragma mark 窗口的代理方法,用户保存数据
  157. -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
  158. //当点击了第二个按钮(OK)
  159. if (buttonIndex==1) {
  160. UITextField *textField= [alertView textFieldAtIndex:0];
  161. //修改模型数据
  162. KCContactGroup *group=_contacts[_selectedIndexPath.section];
  163. KCContact *contact=group.contacts[_selectedIndexPath.row];
  164. contact.phoneNumber=textField.text;
  165. //刷新表格
  166. NSArray *indexPaths=@[_selectedIndexPath];//需要局部刷新的单元格的组、行
  167. [_tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];//后面的参数代码更新时的动画
  168. }
  169. }
  170. #pragma mark 重写状态样式方法
  171. -(UIStatusBarStyle)preferredStatusBarStyle{
  172. return UIStatusBarStyleLightContent;
  173. }
  174. #pragma mark 切换开关转化事件
  175. -(void)switchValueChange:(UISwitch *)sw{
  176. NSLog(@"section:%i,switch:%i",sw.tag, sw.on);
  177. }
  178. @end
最终运行效果:
UITableView全面解析
注意:
1.由于此时我们需要两种UITableViewCell样式,考虑到性能我们需要在缓存池缓存两种Cell。
2.UISwitch继承于UIControl而不是UIView(当然UIControl最终也是继承于UIView),继承于UIControl的控件使用addTarget添加对应事件而不是代理,同时有“是否可用”、“是否高亮”、“是否选中”等属性;
3.上面代码中如果有些UITableViewCell的UISwitch设置为on当其他控件重用时状态也是on,解决这个问题可以在模型中设置对应的属性记录其状态,在生成cell时设置当前状态(为了尽可能简化上面的代码这里就不再修复这个问题);
2.自定义UITableViewCell
虽然系统自带的UITableViewCell已经够强大了,但是很多时候这并不能满足我们的需求。例如新浪微博的Cell就没有那么简单:
UITableView全面解析
没错,这个界面布局也是UITableView实现的,其中的内容就是UITableViewCell,只是这个UITableViewCell是用户自定义实现的。当然要实现上面的UITableViewCell三言两语我们是说不完的,这里我们实现一个简化版本,界面原型如下:
UITableView全面解析
我们对具体控件进行拆分:
UITableView全面解析
在这个界面中有2个UIImageView控件和4个UILabel,整个界面显示效果类似于新浪微博的消息内容界面,但是又在新浪微博基础上进行了精简以至于利用现有知识能够顺利开发出来。
在前面的内容中我们的数据都是手动构建的,在实际开发中自然不会这么做,这里我们不妨将微博数据存储到plist文件中然后从plist文件读取数据构建模型对象(实际开发微博当然需要进行网络数据请求,这里只是进行模拟就不再演示网络请求的内容)。假设plist文件内容如下:
UITableView全面解析
接下来就定义一个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. #import
  9. @interface KCStatus : NSObject
  10. #pragma mark - 属性
  11. @property (nonatomic,assign) long long Id;//微博id
  12. @property (nonatomic,copy) NSString *profileImageUrl;//头像
  13. @property (nonatomic,copy) NSString *userName;//发送用户
  14. @property (nonatomic,assign) NSString *mbtype;//会员类型
  15. @property (nonatomic,copy) NSString *createdAt;//创建时间
  16. @property (nonatomic,copy) NSString *source;//设备来源
  17. @property (nonatomic,copy) NSString *text;//微博内容
  18. #pragma mark - 方法
  19. #pragma mark 根据字典初始化微博对象
  20. -(KCStatus *)initWithDictionary:(NSDictionary *)dic;
  21. #pragma mark 初始化微博对象(静态方法)
  22. +(KCStatus *)statusWithDictionary:(NSDictionary *)dic;
  23. @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. #import "KCStatus.h"
  9. @implementation KCStatus
  10. #pragma mark 根据字典初始化微博对象
  11. -(KCStatus *)initWithDictionary:(NSDictionary *)dic{
  12. if(self=[super init]){
  13. self.Id=[dic[@"Id"] longLongValue];
  14. self.profileImageUrl=dic[@"profileImageUrl"];
  15. self.userName=dic[@"userName"];
  16. self.mbtype=dic[@"mbtype"];
  17. self.createdAt=dic[@"createdAt"];
  18. self.source=dic[@"source"];
  19. self.text=dic[@"text"];
  20. }
  21. return self;
  22. }
  23. #pragma mark 初始化微博对象(静态方法)
  24. +(KCStatus *)statusWithDictionary:(NSDictionary *)dic{
  25. KCStatus *status=[[KCStatus alloc]initWithDictionary:dic];
  26. return status;
  27. }
  28. -(NSString *)source{
  29. return [NSString stringWithFormat:@"来自 %@",_source];
  30. }
  31. @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. #import
  9. @class KCStatus;
  10. @interface KCStatusTableViewCell : UITableViewCell
  11. #pragma mark 微博对象
  12. @property (nonatomic,strong) KCStatus *status;
  13. #pragma mark 单元格高度
  14. @property (assign,nonatomic) CGFloat height;
  15. @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. #import "KCStatusTableViewCell.h"
  9. #import "KCStatus.h"
  10. #define KCColor(r,g,b) [UIColor colorWithHue:r/255.0 saturation:g/255.0 brightness:b/255.0 alpha:1] //颜色宏定义
  11. #define kStatusTableViewCellControlSpacing 10 //控件间距
  12. #define kStatusTableViewCellBackgroundColor KCColor(251,251,251)
  13. #define kStatusGrayColor KCColor(50,50,50)
  14. #define kStatusLightGrayColor KCColor(120,120,120)
  15. #define kStatusTableViewCellAvatarWidth 40 //头像宽度
  16. #define kStatusTableViewCellAvatarHeight kStatusTableViewCellAvatarWidth
  17. #define kStatusTableViewCellUserNameFontSize 14
  18. #define kStatusTableViewCellMbTypeWidth 13 //会员图标宽度
  19. #define kStatusTableViewCellMbTypeHeight kStatusTableViewCellMbTypeWidth
  20. #define kStatusTableViewCellCreateAtFontSize 12
  21. #define kStatusTableViewCellSourceFontSize 12
  22. #define kStatusTableViewCellTextFontSize 14
  23. @interface KCStatusTableViewCell(){
  24. UIImageView *_avatar;//头像
  25. UIImageView *_mbType;//会员类型
  26. UILabel *_userName;
  27. UILabel *_createAt;
  28. UILabel *_source;
  29. UILabel *_text;
  30. }
  31. @end
  32. @implementation KCStatusTableViewCell
  33. - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
  34. self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
  35. if (self) {
  36. [self initSubView];
  37. }
  38. return self;
  39. }
  40. #pragma mark 初始化视图
  41. -(void)initSubView{
  42. //头像控件
  43. _avatar=[[UIImageView alloc]init];
  44. [self addSubview:_avatar];
  45. //用户名
  46. _userName=[[UILabel alloc]init];
  47. _userName.textColor=kStatusGrayColor;
  48. _userName.font=[UIFont systemFontOfSize:kStatusTableViewCellUserNameFontSize];
  49. [self addSubview:_userName];
  50. //会员类型
  51. _mbType=[[UIImageView alloc]init];
  52. [self addSubview:_mbType];
  53. //日期
  54. _createAt=[[UILabel alloc]init];
  55. _createAt.textColor=kStatusLightGrayColor;
  56. _createAt.font=[UIFont systemFontOfSize:kStatusTableViewCellCreateAtFontSize];
  57. [self addSubview:_createAt];
  58. //设备
  59. _source=[[UILabel alloc]init];
  60. _source.textColor=kStatusLightGrayColor;
  61. _source.font=[UIFont systemFontOfSize:kStatusTableViewCellSourceFontSize];
  62. [self addSubview:_source];
  63. //内容
  64. _text=[[UILabel alloc]init];
  65. _text.textColor=kStatusGrayColor;
  66. _text.font=[UIFont systemFontOfSize:kStatusTableViewCellTextFontSize];
  67. _text.numberOfLines=0;
  68. //    _text.lineBreakMode=NSLineBreakByWordWrapping;
  69. [self addSubview:_text];
  70. }
  71. #pragma mark 设置微博
  72. -(void)setStatus:(KCStatus *)status{
  73. //设置头像大小和位置
  74. CGFloat avatarX=10,avatarY=10;
  75. CGRect avatarRect=CGRectMake(avatarX, avatarY, kStatusTableViewCellAvatarWidth, kStatusTableViewCellAvatarHeight);
  76. _avatar.image=[UIImage imageNamed:status.profileImageUrl];
  77. _avatar.frame=avatarRect;
  78. //设置会员图标大小和位置
  79. CGFloat userNameX= CGRectGetMaxX(_avatar.frame)+kStatusTableViewCellControlSpacing ;
  80. CGFloat userNameY=avatarY;
  81. //根据文本内容取得文本占用空间大小
  82. CGSize userNameSize=[status.userName sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:kStatusTableViewCellUserNameFontSize]}];
  83. CGRect userNameRect=CGRectMake(userNameX, userNameY, userNameSize.width,userNameSize.height);
  84. _userName.text=status.userName;
  85. _userName.frame=userNameRect;
  86. //设置会员图标大小和位置
  87. CGFloat mbTypeX=CGRectGetMaxX(_userName.frame)+kStatusTableViewCellControlSpacing;
  88. CGFloat mbTypeY=avatarY;
  89. CGRect mbTypeRect=CGRectMake(mbTypeX, mbTypeY, kStatusTableViewCellMbTypeWidth, kStatusTableViewCellMbTypeHeight);
  90. _mbType.image=[UIImage imageNamed:status.mbtype];
  91. _mbType.frame=mbTypeRect;
  92. //设置发布日期大小和位置
  93. CGSize createAtSize=[status.createdAt sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kStatusTableViewCellCreateAtFontSize]}];
  94. CGFloat createAtX=userNameX;
  95. CGFloat createAtY=CGRectGetMaxY(_avatar.frame)-createAtSize.height;
  96. CGRect createAtRect=CGRectMake(createAtX, createAtY, createAtSize.width, createAtSize.height);
  97. _createAt.text=status.createdAt;
  98. _createAt.frame=createAtRect;
  99. //设置设备信息大小和位置
  100. CGSize sourceSize=[status.source sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kStatusTableViewCellSourceFontSize]}];
  101. CGFloat sourceX=CGRectGetMaxX(_createAt.frame)+kStatusTableViewCellControlSpacing;
  102. CGFloat sourceY=createAtY;
  103. CGRect sourceRect=CGRectMake(sourceX, sourceY, sourceSize.width,sourceSize.height);
  104. _source.text=status.source;
  105. _source.frame=sourceRect;
  106. //设置微博内容大小和位置
  107. CGFloat textX=avatarX;
  108. CGFloat textY=CGRectGetMaxY(_avatar.frame)+kStatusTableViewCellControlSpacing;
  109. CGFloat textWidth=self.frame.size.width-kStatusTableViewCellControlSpacing*2;
  110. CGSize textSize=[status.text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:kStatusTableViewCellTextFontSize]} context:nil].size;
  111. CGRect textRect=CGRectMake(textX, textY, textSize.width, textSize.height);
  112. _text.text=status.text;
  113. _text.frame=textRect;
  114. _height=CGRectGetMaxY(_text.frame)+kStatusTableViewCellControlSpacing;
  115. }
  116. #pragma mark 重写选择事件,取消选中
  117. -(void)setSelected:(BOOL)selected animated:(BOOL)animated{
  118. }
  119. @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. #import "KCStatusCellViewController.h"
  9. #import "KCStatus.h"
  10. #import "KCStatusTableViewCell.h"
  11. @interface KCStatusCellViewController ()<uitableviewdatasource,uitableviewdelegate,uialertviewdelegate>{
  12. UITableView *_tableView;
  13. NSMutableArray *_status;
  14. NSMutableArray *_statusCells;//存储cell,用于计算高度
  15. }
  16. @end
  17. @implementation KCStatusCellViewController
  18. - (void)viewDidLoad {
  19. [super viewDidLoad];
  20. //初始化数据
  21. [self initData];
  22. //创建一个分组样式的UITableView
  23. _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
  24. //设置数据源,注意必须实现对应的UITableViewDataSource协议
  25. _tableView.dataSource=self;
  26. //设置代理
  27. _tableView.delegate=self;
  28. [self.view addSubview:_tableView];
  29. }
  30. #pragma mark 加载数据
  31. -(void)initData{
  32. NSString *path=[[NSBundle mainBundle] pathForResource:@"StatusInfo" ofType:@"plist"];
  33. NSArray *array=[NSArray arrayWithContentsOfFile:path];
  34. _status=[[NSMutableArray alloc]init];
  35. _statusCells=[[NSMutableArray alloc]init];
  36. [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  37. [_status addObject:[KCStatus statusWithDictionary:obj]];
  38. KCStatusTableViewCell *cell=[[KCStatusTableViewCell alloc]init];
  39. [_statusCells addObject:cell];
  40. }];
  41. }
  42. #pragma mark - 数据源方法
  43. #pragma mark 返回分组数
  44. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  45. return 1;
  46. }
  47. #pragma mark 返回每组行数
  48. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  49. return _status.count;
  50. }
  51. #pragma mark返回每行的单元格
  52. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  53. static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1";
  54. KCStatusTableViewCell *cell;
  55. cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  56. if(!cell){
  57. cell=[[KCStatusTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
  58. }
  59. //在此设置微博,以便重新布局
  60. KCStatus *status=_status[indexPath.row];
  61. cell.status=status;
  62. return cell;
  63. }
  64. #pragma mark - 代理方法
  65. #pragma mark 重新设置单元格高度
  66. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  67. //KCStatusTableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
  68. KCStatusTableViewCell *cell= _statusCells[indexPath.row];
  69. cell.status=_status[indexPath.row];
  70. return cell.height;
  71. }
  72. #pragma mark 重写状态样式方法
  73. -(UIStatusBarStyle)preferredStatusBarStyle{
  74. return UIStatusBarStyleLightContent;
  75. }
  76. @end
这个类中需要重点强调一下:Cell的高度需要重新设置(前面说过无论Cell内部设置多高都没有用,需要重新设置),这里采用的方法是首先创建对应的Cell,然后在- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;方法中设置微博数据计算高度通知UITableView。
最后我们看一下运行的效果:
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;
  12. }
1.删除
在UITableView中无论是删除操作还是添加操作都是通过修改UITableView的编辑状态来改变的(除非你不用UITableView自带的删除功能)。在删除按钮中我们设置UITableView的编辑状态:
  1. #pragma mark 删除
  2. -(void)remove{
  3. //直接通过下面的方法设置编辑状态没有动画
  4. //_tableView.editing=!_tableView.isEditing;
  5. [_tableView setEditing:!_tableView.isEditing animated:true];
  6. }
点击删除按钮会在Cell的左侧显示删除按钮:
UITableView全面解析
此时点击左侧删除图标右侧出现删除:
UITableView全面解析
用过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. if (group.contacts.count==0) {
  14. [_contacts removeObject:group];
  15. [tableView reloadData];
  16. }
  17. }
  18. }
从这段代码我们再次看到了MVC的思想,要修改UI先修改数据。而且我们看到了另一个刷新表格的方法- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;,使用这个方法可以再删除之后刷新对应的单元格。效果如下:
UITableView全面解析
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. }
  8. #pragma mark 编辑操作(删除或添加)
  9. //实现了此方法向左滑动就会显示删除(或添加)图标
  10. -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
  11. KCContactGroup *group =_contacts[indexPath.section];
  12. KCContact *contact=group.contacts[indexPath.row];
  13. if (editingStyle==UITableViewCellEditingStyleDelete) {
  14. [group.contacts removeObject:contact];
  15. //考虑到性能这里不建议使用reloadData
  16. //[tableView reloadData];
  17. //使用下面的方法既可以局部刷新又有动画效果
  18. [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
  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. }
  32. }
运行效果:
UITableView全面解析
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. [sourceGroup.contacts removeObject:sourceContact];
  8. if(sourceGroup.contacts.count==0){
  9. [_contacts removeObject:sourceGroup];
  10. [tableView reloadData];
  11. }
  12. [destinationGroup.contacts insertObject:sourceContact atIndex:destinationIndexPath.row];
  13. }
运行效果:
UITableView全面解析
最后给大家附上上面几种操作的完整代码:
  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. }
  19. @end
  20. @implementation KCContactViewController
  21. - (void)viewDidLoad {
  22. [super viewDidLoad];
  23. //初始化数据
  24. [self initData];
  25. //创建一个分组样式的UITableView
  26. _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
  27. _tableView.contentInset=UIEdgeInsetsMake(kContactToolbarHeight, 0, 0, 0);
  28. [self.view addSubview:_tableView];
  29. //添加工具栏
  30. [self addToolbar];
  31. //设置数据源,注意必须实现对应的UITableViewDataSource协议
  32. _tableView.dataSource=self;
  33. //设置代理
  34. _tableView.delegate=self;
  35. }
  36. #pragma mark 加载数据
  37. -(void)initData{
  38. _contacts=[[NSMutableArray alloc]init];
  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. KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"];
  44. KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"];
  45. KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"];
  46. KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]];
  47. [_contacts addObject:group2];
  48. KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"];
  49. KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"];
  50. KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]];
  51. [_contacts addObject:group3];
  52. KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"];
  53. KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"];
  54. KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"];
  55. KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"];
  56. KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"];
  57. KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]];
  58. [_contacts addObject:group4];
  59. KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"];
  60. KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"];
  61. KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"];
  62. KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]];
  63. [_contacts addObject:group5];
  64. }
  65. #pragma mark 添加工具栏
  66. -(void)addToolbar{
  67. CGRect frame=self.view.frame;
  68. _toolbar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, kContactToolbarHeight)];
  69. //    _toolbar.backgroundColor=[UIColor colorWithHue:246/255.0 saturation:246/255.0 brightness:246/255.0 alpha:1];
  70. [self.view addSubview:_toolbar];
  71. UIBarButtonItem *removeButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(remove)];
  72. UIBarButtonItem *flexibleButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
  73. UIBarButtonItem *addButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add)];
  74. NSArray *buttonArray=[NSArray arrayWithObjects:removeButton,flexibleButton,addButton, nil];
  75. _toolbar.items=buttonArray;
  76. }
  77. #pragma mark 删除
  78. -(void)remove{
  79. //直接通过下面的方法设置编辑状态没有动画
  80. //_tableView.editing=!_tableView.isEditing;
  81. _isInsert=false;
  82. [_tableView setEditing:!_tableView.isEditing animated:true];
  83. }
  84. #pragma mark 添加
  85. -(void)add{
  86. _isInsert=true;
  87. [_tableView setEditing:!_tableView.isEditing animated:true];
  88. }
  89. #pragma mark - 数据源方法
  90. #pragma mark 返回分组数
  91. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  92. return _contacts.count;
  93. }
  94. #pragma mark 返回每组行数
  95. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  96. KCContactGroup *group1=_contacts[section];
  97. return group1.contacts.count;
  98. }
  99. #pragma mark返回每行的单元格
  100. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  101. //NSIndexPath是一个对象,记录了组和行信息
  102. KCContactGroup *group=_contacts[indexPath.section];
  103. KCContact *contact=group.contacts[indexPath.row];
  104. static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1";
  105. //首先根据标识去缓存池取
  106. UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  107. //如果缓存池没有取到则重新创建并放到缓存池中
  108. if(!cell){
  109. cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
  110. }
  111. cell.textLabel.text=[contact getName];
  112. cell.detailTextLabel.text=contact.phoneNumber;
  113. return cell;
  114. }
  115. #pragma mark - 代理方法
  116. #pragma mark 设置分组标题
  117. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
  118. KCContactGroup *group=_contacts[section];
  119. return group.name;
  120. }
  121. #pragma mark 编辑操作(删除或添加)
  122. //实现了此方法向左滑动就会显示删除(或添加)图标
  123. -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
  124. KCContactGroup *group =_contacts[indexPath.section];
  125. KCContact *contact=group.contacts[indexPath.row];
  126. if (editingStyle==UITableViewCellEditingStyleDelete) {
  127. [group.contacts removeObject:contact];
  128. //考虑到性能这里不建议使用reloadData
  129. //[tableView reloadData];
  130. //使用下面的方法既可以局部刷新又有动画效果
  131. [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
  132. //如果当前组中没有数据则移除组刷新整个表格
  133. if (group.contacts.count==0) {
  134. [_contacts removeObject:group];
  135. [tableView reloadData];
  136. }
  137. }else if(editingStyle==UITableViewCellEditingStyleInsert){
  138. KCContact *newContact=[[KCContact alloc]init];
  139. newContact.firstName=@"first";
  140. newContact.lastName=@"last";
  141. newContact.phoneNumber=@"12345678901";
  142. [group.contacts insertObject:newContact atIndex:indexPath.row];
  143. [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];//注意这里没有使用reladData刷新
  144. }
  145. }
  146. #pragma mark 排序
  147. //只要实现这个方法在编辑状态右侧就有排序图标
  148. -(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
  149. KCContactGroup *sourceGroup =_contacts[sourceIndexPath.section];
  150. KCContact *sourceContact=sourceGroup.contacts[sourceIndexPath.row];
  151. KCContactGroup *destinationGroup =_contacts[destinationIndexPath.section];
  152. [sourceGroup.contacts removeObject:sourceContact];
  153. [destinationGroup.contacts insertObject:sourceContact atIndex:destinationIndexPath.row];
  154. if(sourceGroup.contacts.count==0){
  155. [_contacts removeObject:sourceGroup];
  156. [tableView reloadData];
  157. }
  158. }
  159. #pragma mark 取得当前操作状态,根据不同的状态左侧出现不同的操作按钮
  160. -(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
  161. if (_isInsert) {
  162. return UITableViewCellEditingStyleInsert;
  163. }
  164. return UITableViewCellEditingStyleDelete;
  165. }
  166. #pragma mark 重写状态样式方法
  167. -(UIStatusBarStyle)preferredStatusBarStyle{
  168. return UIStatusBarStyleLightContent;
  169. }
  170. @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 (){
  13. UITableView *_tableView;
  14. UISearchBar *_searchBar;
  15. //UISearchDisplayController *_searchDisplayController;
  16. NSMutableArray *_contacts;//联系人模型
  17. NSMutableArray *_searchContacts;//符合条件的搜索联系人
  18. BOOL _isSearching;
  19. }
  20. @end
  21. @implementation KCContactTableViewController
  22. - (void)viewDidLoad {
  23. [super viewDidLoad];
  24. //初始化数据
  25. [self initData];
  26. //添加搜索框
  27. [self addSearchBar];
  28. }
  29. #pragma mark - 数据源方法
  30. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  31. if (_isSearching) {
  32. return 1;
  33. }
  34. return _contacts.count;;
  35. }
  36. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  37. if (_isSearching) {
  38. return _searchContacts.count;
  39. }
  40. KCContactGroup *group1=_contacts[section];
  41. return group1.contacts.count;
  42. }
  43. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  44. KCContact *contact=nil;
  45. if (_isSearching) {
  46. contact=_searchContacts[indexPath.row];
  47. }else{
  48. KCContactGroup *group=_contacts[indexPath.section];
  49. contact=group.contacts[indexPath.row];
  50. }
  51. static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1";
  52. //首先根据标识去缓存池取
  53. UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  54. //如果缓存池没有取到则重新创建并放到缓存池中
  55. if(!cell){
  56. cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
  57. }
  58. cell.textLabel.text=[contact getName];
  59. cell.detailTextLabel.text=contact.phoneNumber;
  60. return cell;
  61. }
  62. #pragma mark - 代理方法
  63. #pragma mark 设置分组标题
  64. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
  65. KCContactGroup *group=_contacts[section];
  66. return group.name;
  67. }
  68. #pragma mark - 搜索框代理
  69. #pragma mark  取消搜索
  70. -(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
  71. _isSearching=NO;
  72. _searchBar.text=@"";
  73. [self.tableView reloadData];
  74. }
  75. #pragma mark 输入搜索关键字
  76. -(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
  77. if([_searchBar.text isEqual:@""]){
  78. _isSearching=NO;
  79. [self.tableView reloadData];
  80. return;
  81. }
  82. [self searchDataWithKeyWord:_searchBar.text];
  83. }
  84. #pragma mark 点击虚拟键盘上的搜索时
  85. -(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
  86. [self searchDataWithKeyWord:_searchBar.text];
  87. [_searchBar resignFirstResponder];//放弃第一响应者对象,关闭虚拟键盘
  88. }
  89. #pragma mark 重写状态样式方法
  90. -(UIStatusBarStyle)preferredStatusBarStyle{
  91. return UIStatusBarStyleLightContent;
  92. }
  93. #pragma mark 加载数据
  94. -(void)initData{
  95. _contacts=[[NSMutableArray alloc]init];
  96. KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"];
  97. KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"];
  98. KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]];
  99. [_contacts addObject:group1];
  100. KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"];
  101. KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"];
  102. KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"];
  103. KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]];
  104. [_contacts addObject:group2];
  105. KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"];
  106. KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"];
  107. KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]];
  108. [_contacts addObject:group3];
  109. KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"];
  110. KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"];
  111. KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"];
  112. KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"];
  113. KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"];
  114. KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]];
  115. [_contacts addObject:group4];
  116. KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"];
  117. KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"];
  118. KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"];
  119. KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]];
  120. [_contacts addObject:group5];
  121. }
  122. #pragma mark 搜索形成新数据
  123. -(void)searchDataWithKeyWord:(NSString *)keyWord{
  124. _isSearching=YES;
  125. _searchContacts=[NSMutableArray array];
  126. [_contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  127. KCContactGroup *group=obj;
  128. [group.contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  129. KCContact *contact=obj;
  130. if ([contact.firstName.uppercaseString containsString:keyWord.uppercaseString]||[contact.lastName.uppercaseString containsString:keyWord.uppercaseString]||[contact.phoneNumber containsString:keyWord]) {
  131. [_searchContacts addObject:contact];
  132. }
  133. }];
  134. }];
  135. //刷新表格
  136. [self.tableView reloadData];
  137. }
  138. #pragma mark 添加搜索栏
  139. -(void)addSearchBar{
  140. CGRect searchBarRect=CGRectMake(0, 0, self.view.frame.size.width, kSearchbarHeight);
  141. _searchBar=[[UISearchBar alloc]initWithFrame:searchBarRect];
  142. _searchBar.placeholder=@"Please input key word...";
  143. //_searchBar.keyboardType=UIKeyboardTypeAlphabet;//键盘类型
  144. //_searchBar.autocorrectionType=UITextAutocorrectionTypeNo;//自动纠错类型
  145. //_searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone;//哪一次shitf被自动按下
  146. _searchBar.showsCancelButton=YES;//显示取消按钮
  147. //添加搜索框到页眉位置
  148. _searchBar.delegate=self;
  149. self.tableView.tableHeaderView=_searchBar;
  150. }
  151. @end
运行效果:
UITableView全面解析
在上面的搜索中除了使用一个_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. }
  20. @end
  21. @implementation KCContactTableViewControllerWithUISearchDisplayController
  22. - (void)viewDidLoad {
  23. [super viewDidLoad];
  24. //初始化数据
  25. [self initData];
  26. //添加搜索框
  27. [self addSearchBar];
  28. }
  29. #pragma mark - 数据源方法
  30. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  31. //    if (_isSearching) {
  32. //        return 1;
  33. //    }
  34. //如果当前是UISearchDisplayController内部的tableView则不分组
  35. if (tableView==self.searchDisplayController.searchResultsTableView) {
  36. return 1;
  37. }
  38. return _contacts.count;;
  39. }
  40. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  41. //    if (_isSearching) {
  42. //        return _searchContacts.count;
  43. //    }
  44. //如果当前是UISearchDisplayController内部的tableView则使用搜索数据
  45. if (tableView==self.searchDisplayController.searchResultsTableView) {
  46. return _searchContacts.count;
  47. }
  48. KCContactGroup *group1=_contacts[section];
  49. return group1.contacts.count;
  50. }
  51. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  52. KCContact *contact=nil;
  53. //    if (_isSearching) {
  54. //        contact=_searchContacts[indexPath.row];
  55. //    }else{
  56. //        KCContactGroup *group=_contacts[indexPath.section];
  57. //        contact=group.contacts[indexPath.row];
  58. //    }
  59. //如果当前是UISearchDisplayController内部的tableView则使用搜索数据
  60. if (tableView==self.searchDisplayController.searchResultsTableView) {
  61. contact=_searchContacts[indexPath.row];
  62. }else{
  63. KCContactGroup *group=_contacts[indexPath.section];
  64. contact=group.contacts[indexPath.row];
  65. }
  66. static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1";
  67. //首先根据标识去缓存池取
  68. UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  69. //如果缓存池没有取到则重新创建并放到缓存池中
  70. if(!cell){
  71. cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
  72. }
  73. cell.textLabel.text=[contact getName];
  74. cell.detailTextLabel.text=contact.phoneNumber;
  75. return cell;
  76. }
  77. #pragma mark - 代理方法
  78. #pragma mark 设置分组标题
  79. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
  80. if (tableView==self.searchDisplayController.searchResultsTableView) {
  81. return @"搜索结果";
  82. }
  83. KCContactGroup *group=_contacts[section];
  84. return group.name;
  85. }
  86. #pragma mark 选中之前
  87. -(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  88. [_searchBar resignFirstResponder];//退出键盘
  89. return indexPath;
  90. }
  91. #pragma mark - 搜索框代理
  92. //#pragma mark  取消搜索
  93. //-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
  94. //    //_isSearching=NO;
  95. //    _searchBar.text=@"";
  96. //    //[self.tableView reloadData];
  97. //    [_searchBar resignFirstResponder];
  98. //}
  99. //
  100. //#pragma mark 输入搜索关键字
  101. //-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
  102. //    if([_searchBar.text isEqual:@""]){
  103. //        //_isSearching=NO;
  104. //        //[self.tableView reloadData];
  105. //        return;
  106. //    }
  107. //    [self searchDataWithKeyWord:_searchBar.text];
  108. //}
  109. //#pragma mark 点击虚拟键盘上的搜索时
  110. //-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
  111. //
  112. //    [self searchDataWithKeyWord:_searchBar.text];
  113. //
  114. //    [_searchBar resignFirstResponder];//放弃第一响应者对象,关闭虚拟键盘
  115. //}
  116. #pragma mark - UISearchDisplayController代理方法
  117. -(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
  118. [self searchDataWithKeyWord:searchString];
  119. return YES;
  120. }
  121. #pragma mark 重写状态样式方法
  122. -(UIStatusBarStyle)preferredStatusBarStyle{
  123. return UIStatusBarStyleLightContent;
  124. }
  125. #pragma mark 加载数据
  126. -(void)initData{
  127. _contacts=[[NSMutableArray alloc]init];
  128. KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"];
  129. KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"];
  130. KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]];
  131. [_contacts addObject:group1];
  132. KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"];
  133. KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"];
  134. KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"];
  135. KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]];
  136. [_contacts addObject:group2];
  137. KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"];
  138. KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"];
  139. KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]];
  140. [_contacts addObject:group3];
  141. KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"];
  142. KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"];
  143. KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"];
  144. KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"];
  145. KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"];
  146. KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]];
  147. [_contacts addObject:group4];
  148. KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"];
  149. KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"];
  150. KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"];
  151. KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]];
  152. [_contacts addObject:group5];
  153. }
  154. #pragma mark 搜索形成新数据
  155. -(void)searchDataWithKeyWord:(NSString *)keyWord{
  156. //_isSearching=YES;
  157. _searchContacts=[NSMutableArray array];
  158. [_contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  159. KCContactGroup *group=obj;
  160. [group.contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  161. KCContact *contact=obj;
  162. if ([contact.firstName.uppercaseString containsString:keyWord.uppercaseString]||[contact.lastName.uppercaseString containsString:keyWord.uppercaseString]||[contact.phoneNumber containsString:keyWord]) {
  163. [_searchContacts addObject:contact];
  164. }
  165. }];
  166. }];
  167. //刷新表格
  168. //[self.tableView reloadData];
  169. }
  170. #pragma mark 添加搜索栏
  171. -(void)addSearchBar{
  172. _searchBar=[[UISearchBar alloc]init];
  173. [_searchBar sizeToFit];//大小自适应容器
  174. _searchBar.placeholder=@"Please input key word...";
  175. _searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone;
  176. _searchBar.showsCancelButton=YES;//显示取消按钮
  177. //添加搜索框到页眉位置
  178. _searchBar.delegate=self;
  179. self.tableView.tableHeaderView=_searchBar;
  180. _searchDisplayController=[[UISearchDisplayController alloc]initWithSearchBar:_searchBar contentsController:self];
  181. _searchDisplayController.delegate=self;
  182. _searchDisplayController.searchResultsDataSource=self;
  183. _searchDisplayController.searchResultsDelegate=self;
  184. [_searchDisplayController setActive:NO animated:YES];
  185. }
  186. @end
运行效果:
UITableView全面解析
注意:如果使用Storyboard或xib方式创建上述代码则无需定义UISearchDisplayController成员变量,因为每个UIViewController中已经有一个searchDisplayController对象。
MVC模式
通过UITableView的学习相信大家对于iOS的MVC已经有一个大致的了解,这里简单的分析一下iOS中MVC模式的设计方式。在iOS中多数数据源视图控件(View)都有一个dataSource属性用于和控制器(Controller)交互,而数据来源我们一般会以数据模型(Model)的形式进行定义,View不直接和模型交互,而是通过Controller间接读取数据。
就拿前面的联系人应用举例,UITableView作为视图(View)并不能直接访问模型Contact,它要显示联系人信息只能通过控制器(Controller)来提供数据源方法。同样的控制器本身就拥有视图控件,可以操作视图,也就是说视图和控制器之间可以互相访问。而模型既不能访问视图也不能访问控制器。具体依赖关系如下图:
UITableView全面解析