在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. #pragma mark 带参数的静态对象初始化方法
  27. +(KCContact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber;
  28. @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.  
  22. -(NSString *)getName{
  23. return [NSString stringWithFormat:@"%@ %@",_lastName,_firstName];
  24. }
  25.  
  26. +(KCContact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber{
  27. KCContact *contact1=[[KCContact alloc]initWithFirstName:firstName andLastName:lastName andPhoneNumber:phoneNumber];
  28. return contact1;
  29. }
  30.  
  31. @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. -(KCContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts{
  14. if (self=[super init]) {
  15. self.name=name;
  16. self.detail=detail;
  17. self.contacts=contacts;
  18. }
  19. return self;
  20. }
  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. }
  26. @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.  
  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. [self.view addSubview:_tableView];
  35. }
  36.  
  37. #pragma mark 加载数据
  38. -(void)initData{
  39. _contacts=[[NSMutableArray alloc]init];
  40.  
  41. KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"];
  42. KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"];
  43. KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]];
  44. [_contacts addObject:group1];
  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. KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"];
  53. KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"];
  54.  
  55. KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]];
  56. [_contacts addObject:group3];
  57.  
  58. KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"];
  59. KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"];
  60. KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"];
  61. KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"];
  62. KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"];
  63. KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]];
  64. [_contacts addObject:group4];
  65.  
  66. KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"];
  67. KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"];
  68. KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"];
  69. KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]];
  70. [_contacts addObject:group5];
  71.  
  72. }
  73.  
  74. #pragma mark - 数据源方法
  75. #pragma mark 返回分组数
  76. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  77. NSLog(@"计算分组数");
  78. return _contacts.count;
  79. }
  80.  
  81. #pragma mark 返回每组行数
  82. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  83. NSLog(@"计算每组(组%i)行数",section);
  84. KCContactGroup *group1=_contacts[section];
  85. return group1.contacts.count;
  86. }
  87.  
  88. #pragma mark返回每行的单元格
  89. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  90. //NSIndexPath是一个结构体,记录了组和行信息
  91. NSLog(@"生成单元格(组:%i,行%i)",indexPath.section,indexPath.row);
  92. KCContactGroup *group=_contacts[indexPath.section];
  93. KCContact *contact=group.contacts[indexPath.row];
  94. UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
  95. cell.textLabel.text=[contact getName];
  96. cell.detailTextLabel.text=contact.phoneNumber;
  97. return cell;
  98. }
  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.  
  107. #pragma mark 返回每组尾部说明
  108. -(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
  109. NSLog(@"生成尾部(组%i)详情",section);
  110. KCContactGroup *group=_contacts[section];
  111. return group.detail;
  112. }
  113. @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;
  9. }

效果如下:

需要注意的是上面几个重点方法的执行顺序,请看下图:

值得指出的是生成单元格的方法并不是一次全部调用,而是只会生产当前显示在界面上的单元格,当用户滚动操作时再显示其他单元格。

注意:随着我们的应用越来越复杂,可能经常需要调试程序,在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.  
  10. #pragma mark 设置每行高度(每行高度可以不一样)
  11. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  12. return 45;
  13. }
  14.  
  15. #pragma mark 设置尾部说明内容高度
  16. -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
  17. return 40;
  18. }

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.  
  19. @end
  20.  
  21. @implementation KCMainViewController
  22.  
  23. - (void)viewDidLoad {
  24. [super viewDidLoad];
  25.  
  26. //初始化数据
  27. [self initData];
  28.  
  29. //创建一个分组样式的UITableView
  30. _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
  31.  
  32. //设置数据源,注意必须实现对应的UITableViewDataSource协议
  33. _tableView.dataSource=self;
  34. //设置代理
  35. _tableView.delegate=self;
  36.  
  37. [self.view addSubview:_tableView];
  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. 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. KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"];
  56. KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"];
  57.  
  58. KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]];
  59. [_contacts addObject:group3];
  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. KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"];
  70. KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"];
  71. KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"];
  72. KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]];
  73. [_contacts addObject:group5];
  74.  
  75. }
  76.  
  77. #pragma mark - 数据源方法
  78. #pragma mark 返回分组数
  79. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  80. NSLog(@"计算分组数");
  81. return _contacts.count;
  82. }
  83.  
  84. #pragma mark 返回每组行数
  85. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  86. NSLog(@"计算每组(组%i)行数",section);
  87. KCContactGroup *group1=_contacts[section];
  88. return group1.contacts.count;
  89. }
  90.  
  91. #pragma mark返回每行的单元格
  92. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  93. //NSIndexPath是一个对象,记录了组和行信息
  94. NSLog(@"生成单元格(组:%i,行%i)",indexPath.section,indexPath.row);
  95. KCContactGroup *group=_contacts[indexPath.section];
  96. KCContact *contact=group.contacts[indexPath.row];
  97. UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
  98. cell.textLabel.text=[contact getName];
  99. cell.detailTextLabel.text=contact.phoneNumber;
  100. return cell;
  101. }
  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.  
  110. #pragma mark 返回每组尾部说明
  111. -(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
  112. NSLog(@"生成尾部(组%i)详情",section);
  113. KCContactGroup *group=_contacts[section];
  114. return group.detail;
  115. }
  116.  
  117. #pragma mark 返回每组标题索引
  118. -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
  119. NSLog(@"生成组索引");
  120. NSMutableArray *indexs=[[NSMutableArray alloc]init];
  121. for(KCContactGroup *group in _contacts){
  122. [indexs addObject:group.name];
  123. }
  124. return indexs;
  125. }
  126.  
  127. #pragma mark - 代理方法
  128. #pragma mark 设置分组标题内容高度
  129. -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
  130. if(section==0){
  131. return 50;
  132. }
  133. return 40;
  134. }
  135.  
  136. #pragma mark 设置每行高度(每行高度可以不一样)
  137. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  138. return 45;
  139. }
  140.  
  141. #pragma mark 设置尾部说明内容高度
  142. -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
  143. return 40;
  144. }
  145.  
  146. #pragma mark 点击行
  147. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  148. _selectedIndexPath=indexPath;
  149. KCContactGroup *group=_contacts[indexPath.section];
  150. KCContact *contact=group.contacts[indexPath.row];
  151. //创建弹出窗口
  152. UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"System Info" message:[contact getName] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
  153. alert.alertViewStyle=UIAlertViewStylePlainTextInput; //设置窗口内容样式
  154. UITextField *textField= [alert textFieldAtIndex:0]; //取得文本框
  155. textField.text=contact.phoneNumber; //设置文本框内容
  156. [alert show]; //显示窗口
  157. }
  158.  
  159. #pragma mark 窗口的代理方法,用户保存数据
  160. -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
  161. //当点击了第二个按钮(OK)
  162. if (buttonIndex==1) {
  163. UITextField *textField= [alertView textFieldAtIndex:0];
  164. //修改模型数据
  165. KCContactGroup *group=_contacts[_selectedIndexPath.section];
  166. KCContact *contact=group.contacts[_selectedIndexPath.row];
  167. contact.phoneNumber=textField.text;
  168. //刷新表格
  169. [_tableView reloadData];
  170. }
  171. }
  172.  
  173. #pragma mark 重写状态样式方法
  174. -(UIStatusBarStyle)preferredStatusBarStyle{
  175. return UIStatusBarStyleLightContent;
  176. }
  177. @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内容即可。

  1. #pragma mark返回每行的单元格
  2. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  3. //NSIndexPath是一个对象,记录了组和行信息
  4. NSLog(@"生成单元格(组:%i,行%i)",indexPath.section,indexPath.row);
  5. KCContactGroup *group=_contacts[indexPath.section];
  6. KCContact *contact=group.contacts[indexPath.row];
  7.  
  8. //由于此方法调用十分频繁,cell的标示声明成静态变量有利于性能优化
  9. static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1";
  10. //首先根据标识去缓存池取
  11. UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  12. //如果缓存池没有到则重新创建并放到缓存池中
  13. if(!cell){
  14. cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
  15. }
  16.  
  17. cell.textLabel.text=[contact getName];
  18. cell.detailTextLabel.text=contact.phoneNumber;
  19. NSLog(@"cell:%@",cell);
  20. return cell;
  21. }

上面的代码中已经打印了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.  
  19. @end
  20.  
  21. @implementation KCMainViewController
  22.  
  23. - (void)viewDidLoad {
  24. [super viewDidLoad];
  25.  
  26. //初始化数据
  27. [self initData];
  28.  
  29. //创建一个分组样式的UITableView
  30. _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
  31.  
  32. //设置数据源,注意必须实现对应的UITableViewDataSource协议
  33. _tableView.dataSource=self;
  34. //设置代理
  35. _tableView.delegate=self;
  36.  
  37. [self.view addSubview:_tableView];
  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. 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. KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"];
  56. KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"];
  57.  
  58. KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]];
  59. [_contacts addObject:group3];
  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. KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"];
  70. KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"];
  71. KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"];
  72. KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]];
  73. [_contacts addObject:group5];
  74.  
  75. }
  76.  
  77. #pragma mark - 数据源方法
  78. #pragma mark 返回分组数
  79. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  80. NSLog(@"计算分组数");
  81. return _contacts.count;
  82. }
  83.  
  84. #pragma mark 返回每组行数
  85. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  86. NSLog(@"计算每组(组%i)行数",section);
  87. KCContactGroup *group1=_contacts[section];
  88. return group1.contacts.count;
  89. }
  90.  
  91. #pragma mark返回每行的单元格
  92. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  93. //NSIndexPath是一个对象,记录了组和行信息
  94. NSLog(@"生成单元格(组:%i,行%i)",indexPath.section,indexPath.row);
  95. KCContactGroup *group=_contacts[indexPath.section];
  96. KCContact *contact=group.contacts[indexPath.row];
  97.  
  98. //由于此方法调用十分频繁,cell的标示声明成静态变量有利于性能优化
  99. static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1";
  100. static NSString *cellIdentifierForFirstRow=@"UITableViewCellIdentifierKeyWithSwitch";
  101. //首先根据标示去缓存池取
  102. UITableViewCell *cell;
  103. if (indexPath.row==0) {
  104. cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifierForFirstRow];
  105. }else{
  106. cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  107. }
  108. //如果缓存池没有取到则重新创建并放到缓存池中
  109. if(!cell){
  110. if (indexPath.row==0) {
  111. cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifierForFirstRow];
  112. UISwitch *sw=[[UISwitch alloc]init];
  113. [sw addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventValueChanged];
  114. cell.accessoryView=sw;
  115.  
  116. }else{
  117. cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
  118. cell.accessoryType=UITableViewCellAccessoryDetailButton;
  119. }
  120. }
  121.  
  122. if(indexPath.row==0){
  123. ((UISwitch *)cell.accessoryView).tag=indexPath.section;
  124. }
  125.  
  126. cell.textLabel.text=[contact getName];
  127. cell.detailTextLabel.text=contact.phoneNumber;
  128. NSLog(@"cell:%@",cell);
  129.  
  130. return cell;
  131. }
  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.  
  140. #pragma mark 返回每组尾部说明
  141. -(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
  142. NSLog(@"生成尾部(组%i)详情",section);
  143. KCContactGroup *group=_contacts[section];
  144. return group.detail;
  145. }
  146.  
  147. #pragma mark 返回每组标题索引
  148. -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
  149. NSLog(@"生成组索引");
  150. NSMutableArray *indexs=[[NSMutableArray alloc]init];
  151. for(KCContactGroup *group in _contacts){
  152. [indexs addObject:group.name];
  153. }
  154. return indexs;
  155. }
  156.  
  157. #pragma mark - 代理方法
  158. #pragma mark 设置分组标题内容高度
  159. -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
  160. if(section==0){
  161. return 50;
  162. }
  163. return 40;
  164. }
  165.  
  166. #pragma mark 设置每行高度(每行高度可以不一样)
  167. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  168. return 45;
  169. }
  170.  
  171. #pragma mark 设置尾部说明内容高度
  172. -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
  173. return 40;
  174. }
  175.  
  176. #pragma mark 点击行
  177. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  178. _selectedIndexPath=indexPath;
  179. KCContactGroup *group=_contacts[indexPath.section];
  180. KCContact *contact=group.contacts[indexPath.row];
  181. //创建弹出窗口
  182. UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"System Info" message:[contact getName] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
  183. alert.alertViewStyle=UIAlertViewStylePlainTextInput; //设置窗口内容样式
  184. UITextField *textField= [alert textFieldAtIndex:0]; //取得文本框
  185. textField.text=contact.phoneNumber; //设置文本框内容
  186. [alert show]; //显示窗口
  187. }
  188.  
  189. #pragma mark 窗口的代理方法,用户保存数据
  190. -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
  191. //当点击了第二个按钮(OK)
  192. if (buttonIndex==1) {
  193. UITextField *textField= [alertView textFieldAtIndex:0];
  194. //修改模型数据
  195. KCContactGroup *group=_contacts[_selectedIndexPath.section];
  196. KCContact *contact=group.contacts[_selectedIndexPath.row];
  197. contact.phoneNumber=textField.text;
  198. //刷新表格
  199. NSArray *indexPaths=@[_selectedIndexPath];//需要局部刷新的单元格的组、行
  200. [_tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];//后面的参数代码更新时的动画
  201. }
  202. }
  203.  
  204. #pragma mark 重写状态样式方法
  205. -(UIStatusBarStyle)preferredStatusBarStyle{
  206. return UIStatusBarStyleLightContent;
  207. }
  208.  
  209. #pragma mark 切换开关转化事件
  210. -(void)switchValueChange:(UISwitch *)sw{
  211. NSLog(@"section:%i,switch:%i",sw.tag, sw.on);
  212. }
  213. @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的代理事件中设置每个单元格高度。

1.首先看一下微博模型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,copy) NSString *mbtype;//会员类型
  18. @property (nonatomic,copy) NSString *createdAt;//创建时间
  19. @property (nonatomic,copy) NSString *source;//设备来源
  20. @property (nonatomic,copy) NSString *text;//微博内容
  21.  
  22. #pragma mark - 方法
  23. #pragma mark 根据字典初始化微博对象
  24. -(KCStatus *)initWithDictionary:(NSDictionary *)dic;
  25.  
  26. #pragma mark 初始化微博对象(静态方法)
  27. +(KCStatus *)statusWithDictionary:(NSDictionary *)dic;
  28. @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.  
  27. #pragma mark 初始化微博对象(静态方法)
  28. +(KCStatus *)statusWithDictionary:(NSDictionary *)dic{
  29. KCStatus *status=[[KCStatus alloc]initWithDictionary:dic];
  30. return status;
  31. }
  32.  
  33. -(NSString *)source{
  34. return [NSString stringWithFormat:@"来自 %@",_source];
  35. }
  36. @end

2.然后看一下自定义的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. @interface KCStatusTableViewCell(){
  27. UIImageView *_avatar;//头像
  28. UIImageView *_mbType;//会员类型
  29. UILabel *_userName;
  30. UILabel *_createAt;
  31. UILabel *_source;
  32. UILabel *_text;
  33. }
  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.  
  47. #pragma mark 初始化视图
  48. -(void)initSubView{
  49. //头像控件
  50. _avatar=[[UIImageView alloc]init];
  51. [self addSubview:_avatar];
  52. //用户名
  53. _userName=[[UILabel alloc]init];
  54. _userName.textColor=kStatusGrayColor;
  55. _userName.font=[UIFont systemFontOfSize:kStatusTableViewCellUserNameFontSize];
  56. [self addSubview:_userName];
  57. //会员类型
  58. _mbType=[[UIImageView alloc]init];
  59. [self addSubview:_mbType];
  60. //日期
  61. _createAt=[[UILabel alloc]init];
  62. _createAt.textColor=kStatusLightGrayColor;
  63. _createAt.font=[UIFont systemFontOfSize:kStatusTableViewCellCreateAtFontSize];
  64. [self addSubview:_createAt];
  65. //设备
  66. _source=[[UILabel alloc]init];
  67. _source.textColor=kStatusLightGrayColor;
  68. _source.font=[UIFont systemFontOfSize:kStatusTableViewCellSourceFontSize];
  69. [self addSubview:_source];
  70. //内容
  71. _text=[[UILabel alloc]init];
  72. _text.textColor=kStatusGrayColor;
  73. _text.font=[UIFont systemFontOfSize:kStatusTableViewCellTextFontSize];
  74. _text.numberOfLines=0;
  75. // _text.lineBreakMode=NSLineBreakByWordWrapping;
  76. [self addSubview:_text];
  77. }
  78.  
  79. #pragma mark 设置微博
  80. -(void)setStatus:(KCStatus *)status{
  81. //设置头像大小和位置
  82. CGFloat avatarX=10,avatarY=10;
  83. CGRect avatarRect=CGRectMake(avatarX, avatarY, kStatusTableViewCellAvatarWidth, kStatusTableViewCellAvatarHeight);
  84. _avatar.image=[UIImage imageNamed:status.profileImageUrl];
  85. _avatar.frame=avatarRect;
  86.  
  87. //设置会员图标大小和位置
  88. CGFloat userNameX= CGRectGetMaxX(_avatar.frame)+kStatusTableViewCellControlSpacing ;
  89. CGFloat userNameY=avatarY;
  90. //根据文本内容取得文本占用空间大小
  91. CGSize userNameSize=[status.userName sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:kStatusTableViewCellUserNameFontSize]}];
  92. CGRect userNameRect=CGRectMake(userNameX, userNameY, userNameSize.width,userNameSize.height);
  93. _userName.text=status.userName;
  94. _userName.frame=userNameRect;
  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. CGSize createAtSize=[status.createdAt sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kStatusTableViewCellCreateAtFontSize]}];
  105. CGFloat createAtX=userNameX;
  106. CGFloat createAtY=CGRectGetMaxY(_avatar.frame)-createAtSize.height;
  107. CGRect createAtRect=CGRectMake(createAtX, createAtY, createAtSize.width, createAtSize.height);
  108. _createAt.text=status.createdAt;
  109. _createAt.frame=createAtRect;
  110.  
  111. //设置设备信息大小和位置
  112. CGSize sourceSize=[status.source sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kStatusTableViewCellSourceFontSize]}];
  113. CGFloat sourceX=CGRectGetMaxX(_createAt.frame)+kStatusTableViewCellControlSpacing;
  114. CGFloat sourceY=createAtY;
  115. CGRect sourceRect=CGRectMake(sourceX, sourceY, sourceSize.width,sourceSize.height);
  116. _source.text=status.source;
  117. _source.frame=sourceRect;
  118.  
  119. //设置微博内容大小和位置
  120. CGFloat textX=avatarX;
  121. CGFloat textY=CGRectGetMaxY(_avatar.frame)+kStatusTableViewCellControlSpacing;
  122. CGFloat textWidth=self.frame.size.width-kStatusTableViewCellControlSpacing*2;
  123. CGSize textSize=[status.text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:kStatusTableViewCellTextFontSize]} context:nil].size;
  124. CGRect textRect=CGRectMake(textX, textY, textSize.width, textSize.height);
  125. _text.text=status.text;
  126. _text.frame=textRect;
  127.  
  128. _height=CGRectGetMaxY(_text.frame)+kStatusTableViewCellControlSpacing;
  129. }
  130.  
  131. #pragma mark 重写选择事件,取消选中
  132. -(void)setSelected:(BOOL)selected animated:(BOOL)animated{
  133.  
  134. }
  135. @end

这是我们自定义Cell这个例子的核心,自定义Cell分为两个步骤:首先要进行各种控件的初始化工作,这个过程中只要将控件放到Cell的View中同时设置控件显示内容的格式(字体大小、颜色等)即可;然后在数据对象设置方法中进行各个控件的布局(大小、位置)。在代码中有几点需要重点提示大家:

  • 对于单行文本数据的显示调用- (CGSize)sizeWithAttributes:(NSDictionary *)attrs;方法来得到文本宽度和高度。
  • 对于多行文本数据的显示调用- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context ;方法来得到文本宽度和高度;同时注意在此之前需要设置文本控件的numberOfLines属性为0。
  • 通常我们会在自定义Cell中设置一个高度属性,用于外界方法调用,因为Cell内部设置Cell的高度是没有用的,UITableViewCell在初始化时会重新设置高度。

3.最后我们看一下自定义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. }
  18. @end
  19.  
  20. @implementation KCStatusCellViewController
  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. _tableView.delegate=self;
  34.  
  35. [self.view addSubview:_tableView];
  36. }
  37.  
  38. #pragma mark 加载数据
  39. -(void)initData{
  40. NSString *path=[[NSBundle mainBundle] pathForResource:@"StatusInfo" ofType:@"plist"];
  41. NSArray *array=[NSArray arrayWithContentsOfFile:path];
  42. _status=[[NSMutableArray alloc]init];
  43. _statusCells=[[NSMutableArray alloc]init];
  44. [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  45. [_status addObject:[KCStatus statusWithDictionary:obj]];
  46. KCStatusTableViewCell *cell=[[KCStatusTableViewCell alloc]init];
  47. [_statusCells addObject:cell];
  48. }];
  49. }
  50. #pragma mark - 数据源方法
  51. #pragma mark 返回分组数
  52. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  53. return 1;
  54. }
  55.  
  56. #pragma mark 返回每组行数
  57. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  58.  
  59. return _status.count;
  60. }
  61.  
  62. #pragma mark返回每行的单元格
  63. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  64. static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1";
  65. KCStatusTableViewCell *cell;
  66. cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  67. if(!cell){
  68. cell=[[KCStatusTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
  69. }
  70. //在此设置微博,以便重新布局
  71. KCStatus *status=_status[indexPath.row];
  72. cell.status=status;
  73. return cell;
  74. }
  75.  
  76. #pragma mark - 代理方法
  77. #pragma mark 重新设置单元格高度
  78. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  79. //KCStatusTableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
  80. KCStatusTableViewCell *cell= _statusCells[indexPath.row];
  81. cell.status=_status[indexPath.row];
  82. return cell.height;
  83. }
  84.  
  85. #pragma mark 重写状态样式方法
  86. -(UIStatusBarStyle)preferredStatusBarStyle{
  87. return UIStatusBarStyleLightContent;
  88. }
  89. @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;
  12. }

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];
  7. }

点击删除按钮会在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. }
  19. }

从这段代码我们再次看到了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. }
  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. //如果当前组中没有数据则移除组刷新整个表格
  21. if (group.contacts.count==0) {
  22. [_contacts removeObject:group];
  23. [tableView reloadData];
  24. }
  25. }else if(editingStyle==UITableViewCellEditingStyleInsert){
  26. KCContact *newContact=[[KCContact alloc]init];
  27. newContact.firstName=@"first";
  28. newContact.lastName=@"last";
  29. newContact.phoneNumber=@"12345678901";
  30. [group.contacts insertObject:newContact atIndex:indexPath.row];
  31. [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];//注意这里没有使用reladData刷新
  32. }
  33. }

运行效果:

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.  
  16. }

运行效果:

最后给大家附上上面几种操作的完整代码:

  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.  
  9. #import "KCContactViewController.h"
  10. #import "KCContact.h"
  11. #import "KCContactGroup.h"
  12. #define kContactToolbarHeight 44
  13.  
  14. @interface KCContactViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>{
  15. UITableView *_tableView;
  16. UIToolbar *_toolbar;
  17. NSMutableArray *_contacts;//联系人模型
  18. NSIndexPath *_selectedIndexPath;//当前选中的组和行
  19. BOOL _isInsert;//记录是点击了插入还是删除按钮
  20. }
  21.  
  22. @end
  23.  
  24. @implementation KCContactViewController
  25.  
  26. - (void)viewDidLoad {
  27. [super viewDidLoad];
  28.  
  29. //初始化数据
  30. [self initData];
  31.  
  32. //创建一个分组样式的UITableView
  33. _tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
  34. _tableView.contentInset=UIEdgeInsetsMake(kContactToolbarHeight, 0, 0, 0);
  35. [self.view addSubview:_tableView];
  36.  
  37. //添加工具栏
  38. [self addToolbar];
  39.  
  40. //设置数据源,注意必须实现对应的UITableViewDataSource协议
  41. _tableView.dataSource=self;
  42. //设置代理
  43. _tableView.delegate=self;
  44.  
  45. }
  46.  
  47. #pragma mark 加载数据
  48. -(void)initData{
  49. _contacts=[[NSMutableArray alloc]init];
  50.  
  51. KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"];
  52. KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"];
  53. KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]];
  54. [_contacts addObject:group1];
  55.  
  56. KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"];
  57. KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"];
  58. KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"];
  59. KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]];
  60. [_contacts addObject:group2];
  61.  
  62. KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"];
  63. KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"];
  64.  
  65. KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]];
  66. [_contacts addObject:group3];
  67.  
  68. KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"];
  69. KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"];
  70. KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"];
  71. KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"];
  72. KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"];
  73. KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]];
  74. [_contacts addObject:group4];
  75.  
  76. KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"];
  77. KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"];
  78. KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"];
  79. KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]];
  80. [_contacts addObject:group5];
  81.  
  82. }
  83.  
  84. #pragma mark 添加工具栏
  85. -(void)addToolbar{
  86. CGRect frame=self.view.frame;
  87. _toolbar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, kContactToolbarHeight)];
  88. // _toolbar.backgroundColor=[UIColor colorWithHue:246/255.0 saturation:246/255.0 brightness:246/255.0 alpha:1];
  89. [self.view addSubview:_toolbar];
  90. UIBarButtonItem *removeButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(remove)];
  91. UIBarButtonItem *flexibleButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
  92. UIBarButtonItem *addButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add)];
  93. NSArray *buttonArray=[NSArray arrayWithObjects:removeButton,flexibleButton,addButton, nil];
  94. _toolbar.items=buttonArray;
  95. }
  96. #pragma mark 删除
  97. -(void)remove{
  98. //直接通过下面的方法设置编辑状态没有动画
  99. //_tableView.editing=!_tableView.isEditing;
  100. _isInsert=false;
  101. [_tableView setEditing:!_tableView.isEditing animated:true];
  102. }
  103. #pragma mark 添加
  104. -(void)add{
  105. _isInsert=true;
  106. [_tableView setEditing:!_tableView.isEditing animated:true];
  107. }
  108.  
  109. #pragma mark - 数据源方法
  110. #pragma mark 返回分组数
  111. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  112. return _contacts.count;
  113. }
  114.  
  115. #pragma mark 返回每组行数
  116. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  117. KCContactGroup *group1=_contacts[section];
  118. return group1.contacts.count;
  119. }
  120.  
  121. #pragma mark返回每行的单元格
  122. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  123. //NSIndexPath是一个对象,记录了组和行信息
  124. KCContactGroup *group=_contacts[indexPath.section];
  125. KCContact *contact=group.contacts[indexPath.row];
  126.  
  127. static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1";
  128.  
  129. //首先根据标识去缓存池取
  130. UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  131. //如果缓存池没有取到则重新创建并放到缓存池中
  132. if(!cell){
  133. cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
  134. }
  135.  
  136. cell.textLabel.text=[contact getName];
  137. cell.detailTextLabel.text=contact.phoneNumber;
  138.  
  139. return cell;
  140. }
  141.  
  142. #pragma mark - 代理方法
  143. #pragma mark 设置分组标题
  144. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
  145. KCContactGroup *group=_contacts[section];
  146. return group.name;
  147. }
  148.  
  149. #pragma mark 编辑操作(删除或添加)
  150. //实现了此方法向左滑动就会显示删除(或添加)图标
  151. -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
  152. KCContactGroup *group =_contacts[indexPath.section];
  153. KCContact *contact=group.contacts[indexPath.row];
  154. if (editingStyle==UITableViewCellEditingStyleDelete) {
  155. [group.contacts removeObject:contact];
  156. //考虑到性能这里不建议使用reloadData
  157. //[tableView reloadData];
  158. //使用下面的方法既可以局部刷新又有动画效果
  159. [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
  160.  
  161. //如果当前组中没有数据则移除组刷新整个表格
  162. if (group.contacts.count==0) {
  163. [_contacts removeObject:group];
  164. [tableView reloadData];
  165. }
  166. }else if(editingStyle==UITableViewCellEditingStyleInsert){
  167. KCContact *newContact=[[KCContact alloc]init];
  168. newContact.firstName=@"first";
  169. newContact.lastName=@"last";
  170. newContact.phoneNumber=@"12345678901";
  171. [group.contacts insertObject:newContact atIndex:indexPath.row];
  172. [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];//注意这里没有使用reladData刷新
  173. }
  174. }
  175.  
  176. #pragma mark 排序
  177. //只要实现这个方法在编辑状态右侧就有排序图标
  178. -(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
  179. KCContactGroup *sourceGroup =_contacts[sourceIndexPath.section];
  180. KCContact *sourceContact=sourceGroup.contacts[sourceIndexPath.row];
  181. KCContactGroup *destinationGroup =_contacts[destinationIndexPath.section];
  182.  
  183. [sourceGroup.contacts removeObject:sourceContact];
  184. [destinationGroup.contacts insertObject:sourceContact atIndex:destinationIndexPath.row];
  185. if(sourceGroup.contacts.count==0){
  186. [_contacts removeObject:sourceGroup];
  187. [tableView reloadData];
  188. }
  189. }
  190.  
  191. #pragma mark 取得当前操作状态,根据不同的状态左侧出现不同的操作按钮
  192. -(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
  193. if (_isInsert) {
  194. return UITableViewCellEditingStyleInsert;
  195. }
  196. return UITableViewCellEditingStyleDelete;
  197. }
  198.  
  199. #pragma mark 重写状态样式方法
  200. -(UIStatusBarStyle)preferredStatusBarStyle{
  201. return UIStatusBarStyleLightContent;
  202. }
  203.  
  204. @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.  
  9. #import "KCContactTableViewController.h"
  10. #import "KCContact.h"
  11. #import "KCContactGroup.h"
  12. #define kSearchbarHeight 44
  13.  
  14. @interface KCContactTableViewController ()<UISearchBarDelegate>{
  15. UITableView *_tableView;
  16. UISearchBar *_searchBar;
  17. //UISearchDisplayController *_searchDisplayController;
  18. NSMutableArray *_contacts;//联系人模型
  19. NSMutableArray *_searchContacts;//符合条件的搜索联系人
  20. BOOL _isSearching;
  21. }
  22. @end
  23.  
  24. @implementation KCContactTableViewController
  25.  
  26. - (void)viewDidLoad {
  27. [super viewDidLoad];
  28. //初始化数据
  29. [self initData];
  30.  
  31. //添加搜索框
  32. [self addSearchBar];
  33.  
  34. }
  35.  
  36. #pragma mark - 数据源方法
  37.  
  38. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  39. if (_isSearching) {
  40. return 1;
  41. }
  42. return _contacts.count;;
  43. }
  44.  
  45. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  46. if (_isSearching) {
  47. return _searchContacts.count;
  48. }
  49. KCContactGroup *group1=_contacts[section];
  50. return group1.contacts.count;
  51. }
  52.  
  53. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  54. KCContact *contact=nil;
  55.  
  56. if (_isSearching) {
  57. contact=_searchContacts[indexPath.row];
  58. }else{
  59. KCContactGroup *group=_contacts[indexPath.section];
  60. contact=group.contacts[indexPath.row];
  61. }
  62.  
  63. static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1";
  64.  
  65. //首先根据标识去缓存池取
  66. UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  67. //如果缓存池没有取到则重新创建并放到缓存池中
  68. if(!cell){
  69. cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
  70. }
  71.  
  72. cell.textLabel.text=[contact getName];
  73. cell.detailTextLabel.text=contact.phoneNumber;
  74.  
  75. return cell;
  76. }
  77.  
  78. #pragma mark - 代理方法
  79. #pragma mark 设置分组标题
  80. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
  81. KCContactGroup *group=_contacts[section];
  82. return group.name;
  83. }
  84.  
  85. #pragma mark - 搜索框代理
  86. #pragma mark 取消搜索
  87. -(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
  88. _isSearching=NO;
  89. _searchBar.text=@"";
  90. [self.tableView reloadData];
  91. }
  92.  
  93. #pragma mark 输入搜索关键字
  94. -(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
  95. if([_searchBar.text isEqual:@""]){
  96. _isSearching=NO;
  97. [self.tableView reloadData];
  98. return;
  99. }
  100. [self searchDataWithKeyWord:_searchBar.text];
  101. }
  102.  
  103. #pragma mark 点击虚拟键盘上的搜索时
  104. -(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
  105.  
  106. [self searchDataWithKeyWord:_searchBar.text];
  107.  
  108. [_searchBar resignFirstResponder];//放弃第一响应者对象,关闭虚拟键盘
  109. }
  110.  
  111. #pragma mark 重写状态样式方法
  112. -(UIStatusBarStyle)preferredStatusBarStyle{
  113. return UIStatusBarStyleLightContent;
  114. }
  115.  
  116. #pragma mark 加载数据
  117. -(void)initData{
  118. _contacts=[[NSMutableArray alloc]init];
  119.  
  120. KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"];
  121. KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"];
  122. KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]];
  123. [_contacts addObject:group1];
  124.  
  125. KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"];
  126. KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"];
  127. KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"];
  128. KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]];
  129. [_contacts addObject:group2];
  130.  
  131. KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"];
  132. KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"];
  133.  
  134. KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]];
  135. [_contacts addObject:group3];
  136.  
  137. KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"];
  138. KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"];
  139. KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"];
  140. KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"];
  141. KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"];
  142. KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]];
  143. [_contacts addObject:group4];
  144.  
  145. KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"];
  146. KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"];
  147. KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"];
  148. KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]];
  149. [_contacts addObject:group5];
  150.  
  151. }
  152.  
  153. #pragma mark 搜索形成新数据
  154. -(void)searchDataWithKeyWord:(NSString *)keyWord{
  155. _isSearching=YES;
  156. _searchContacts=[NSMutableArray array];
  157. [_contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  158. KCContactGroup *group=obj;
  159. [group.contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  160. KCContact *contact=obj;
  161. if ([contact.firstName.uppercaseString containsString:keyWord.uppercaseString]||[contact.lastName.uppercaseString containsString:keyWord.uppercaseString]||[contact.phoneNumber containsString:keyWord]) {
  162. [_searchContacts addObject:contact];
  163. }
  164. }];
  165. }];
  166.  
  167. //刷新表格
  168. [self.tableView reloadData];
  169. }
  170.  
  171. #pragma mark 添加搜索栏
  172. -(void)addSearchBar{
  173. CGRect searchBarRect=CGRectMake(0, 0, self.view.frame.size.width, kSearchbarHeight);
  174. _searchBar=[[UISearchBar alloc]initWithFrame:searchBarRect];
  175. _searchBar.placeholder=@"Please input key word...";
  176. //_searchBar.keyboardType=UIKeyboardTypeAlphabet;//键盘类型
  177. //_searchBar.autocorrectionType=UITextAutocorrectionTypeNo;//自动纠错类型
  178. //_searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone;//哪一次shitf被自动按下
  179. _searchBar.showsCancelButton=YES;//显示取消按钮
  180. //添加搜索框到页眉位置
  181. _searchBar.delegate=self;
  182. self.tableView.tableHeaderView=_searchBar;
  183. }
  184.  
  185. @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.  
  9. #import "KCContactTableViewControllerWithUISearchDisplayController.h"
  10. #import "KCContact.h"
  11. #import "KCContactGroup.h"
  12. #define kSearchbarHeight 44
  13.  
  14. @interface KCContactTableViewControllerWithUISearchDisplayController ()<UISearchBarDelegate,UISearchDisplayDelegate>{
  15. UITableView *_tableView;
  16. UISearchBar *_searchBar;
  17. UISearchDisplayController *_searchDisplayController;
  18. NSMutableArray *_contacts;//联系人模型
  19. NSMutableArray *_searchContacts;//符合条件的搜索联系人
  20. //BOOL _isSearching;
  21. }
  22. @end
  23.  
  24. @implementation KCContactTableViewControllerWithUISearchDisplayController
  25.  
  26. - (void)viewDidLoad {
  27. [super viewDidLoad];
  28. //初始化数据
  29. [self initData];
  30.  
  31. //添加搜索框
  32. [self addSearchBar];
  33.  
  34. }
  35.  
  36. #pragma mark - 数据源方法
  37.  
  38. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  39. // if (_isSearching) {
  40. // return 1;
  41. // }
  42. //如果当前是UISearchDisplayController内部的tableView则不分组
  43. if (tableView==self.searchDisplayController.searchResultsTableView) {
  44. return 1;
  45. }
  46. return _contacts.count;;
  47. }
  48.  
  49. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  50. // if (_isSearching) {
  51. // return _searchContacts.count;
  52. // }
  53. //如果当前是UISearchDisplayController内部的tableView则使用搜索数据
  54. if (tableView==self.searchDisplayController.searchResultsTableView) {
  55. return _searchContacts.count;
  56. }
  57. KCContactGroup *group1=_contacts[section];
  58. return group1.contacts.count;
  59. }
  60.  
  61. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  62. KCContact *contact=nil;
  63.  
  64. // if (_isSearching) {
  65. // contact=_searchContacts[indexPath.row];
  66. // }else{
  67. // KCContactGroup *group=_contacts[indexPath.section];
  68. // contact=group.contacts[indexPath.row];
  69. // }
  70. //如果当前是UISearchDisplayController内部的tableView则使用搜索数据
  71. if (tableView==self.searchDisplayController.searchResultsTableView) {
  72. contact=_searchContacts[indexPath.row];
  73. }else{
  74. KCContactGroup *group=_contacts[indexPath.section];
  75. contact=group.contacts[indexPath.row];
  76. }
  77.  
  78. static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1";
  79.  
  80. //首先根据标识去缓存池取
  81. UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  82. //如果缓存池没有取到则重新创建并放到缓存池中
  83. if(!cell){
  84. cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
  85. }
  86.  
  87. cell.textLabel.text=[contact getName];
  88. cell.detailTextLabel.text=contact.phoneNumber;
  89.  
  90. return cell;
  91. }
  92.  
  93. #pragma mark - 代理方法
  94. #pragma mark 设置分组标题
  95. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
  96. if (tableView==self.searchDisplayController.searchResultsTableView) {
  97. return @"搜索结果";
  98. }
  99. KCContactGroup *group=_contacts[section];
  100. return group.name;
  101. }
  102. #pragma mark 选中之前
  103. -(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  104. [_searchBar resignFirstResponder];//退出键盘
  105. return indexPath;
  106. }
  107.  
  108. #pragma mark - 搜索框代理
  109. //#pragma mark 取消搜索
  110. //-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
  111. // //_isSearching=NO;
  112. // _searchBar.text=@"";
  113. // //[self.tableView reloadData];
  114. // [_searchBar resignFirstResponder];
  115. //}
  116. //
  117. //#pragma mark 输入搜索关键字
  118. //-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
  119. // if([_searchBar.text isEqual:@""]){
  120. // //_isSearching=NO;
  121. // //[self.tableView reloadData];
  122. // return;
  123. // }
  124. // [self searchDataWithKeyWord:_searchBar.text];
  125. //}
  126.  
  127. //#pragma mark 点击虚拟键盘上的搜索时
  128. //-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
  129. //
  130. // [self searchDataWithKeyWord:_searchBar.text];
  131. //
  132. // [_searchBar resignFirstResponder];//放弃第一响应者对象,关闭虚拟键盘
  133. //}
  134.  
  135. #pragma mark - UISearchDisplayController代理方法
  136. -(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
  137. [self searchDataWithKeyWord:searchString];
  138. return YES;
  139. }
  140.  
  141. #pragma mark 重写状态样式方法
  142. -(UIStatusBarStyle)preferredStatusBarStyle{
  143. return UIStatusBarStyleLightContent;
  144. }
  145.  
  146. #pragma mark 加载数据
  147. -(void)initData{
  148. _contacts=[[NSMutableArray alloc]init];
  149.  
  150. KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"];
  151. KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"];
  152. KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]];
  153. [_contacts addObject:group1];
  154.  
  155. KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"];
  156. KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"];
  157. KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"];
  158. KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]];
  159. [_contacts addObject:group2];
  160.  
  161. KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"];
  162. KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"];
  163.  
  164. KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]];
  165. [_contacts addObject:group3];
  166.  
  167. KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"];
  168. KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"];
  169. KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"];
  170. KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"];
  171. KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"];
  172. KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]];
  173. [_contacts addObject:group4];
  174.  
  175. KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"];
  176. KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"];
  177. KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"];
  178. KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]];
  179. [_contacts addObject:group5];
  180.  
  181. }
  182.  
  183. #pragma mark 搜索形成新数据
  184. -(void)searchDataWithKeyWord:(NSString *)keyWord{
  185. //_isSearching=YES;
  186. _searchContacts=[NSMutableArray array];
  187. [_contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  188. KCContactGroup *group=obj;
  189. [group.contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  190. KCContact *contact=obj;
  191. if ([contact.firstName.uppercaseString containsString:keyWord.uppercaseString]||[contact.lastName.uppercaseString containsString:keyWord.uppercaseString]||[contact.phoneNumber containsString:keyWord]) {
  192. [_searchContacts addObject:contact];
  193. }
  194. }];
  195. }];
  196.  
  197. //刷新表格
  198. //[self.tableView reloadData];
  199. }
  200.  
  201. #pragma mark 添加搜索栏
  202. -(void)addSearchBar{
  203. _searchBar=[[UISearchBar alloc]init];
  204. [_searchBar sizeToFit];//大小自适应容器
  205. _searchBar.placeholder=@"Please input key word...";
  206. _searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone;
  207. _searchBar.showsCancelButton=YES;//显示取消按钮
  208. //添加搜索框到页眉位置
  209. _searchBar.delegate=self;
  210. self.tableView.tableHeaderView=_searchBar;
  211.  
  212. _searchDisplayController=[[UISearchDisplayController alloc]initWithSearchBar:_searchBar contentsController:self];
  213. _searchDisplayController.delegate=self;
  214. _searchDisplayController.searchResultsDataSource=self;
  215. _searchDisplayController.searchResultsDelegate=self;
  216. [_searchDisplayController setActive:NO animated:YES];
  217.  
  218. }
  219.  
  220. @end

运行效果:

注意如果使用Storyboard或xib方式创建上述代码则无需定义UISearchDisplayController成员变量,因为每个UIViewController中已经有一个searchDisplayController对象。

MVC模式

通过UITableView的学习相信大家对于iOS的MVC已经有一个大致的了解,这里简单的分析一下iOS中MVC模式的设计方式。在iOS中多数数据源视图控件(View)都有一个dataSource属性用于和控制器(Controller)交互,而数据来源我们一般会以数据模型(Model)的形式进行定义,View不直接和模型交互,而是通过Controller间接读取数据。

就拿前面的联系人应用举例,UITableView作为视图(View)并不能直接访问模型Contact,它要显示联系人信息只能通过控制器(Controller)来提供数据源方法。同样的控制器本身就拥有视图控件,可以操作视图,也就是说视图和控制器之间可以互相访问。而模型既不能访问视图也不能访问控制器。具体依赖关系如下图:

UITableView 全面详解的更多相关文章

  1. (转载)UITableView使用详解

    在开发iphone的应用时基本上都要用到UITableView,这里讲解一下UITableView的使用方法及代理的调用情况 UITableView使用详解 - (void)viewDidLoad { ...

  2. IOS中表视图(UITableView)使用详解

    IOS中UITableView使用总结 一.初始化方法 - (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)styl ...

  3. UITableView 实例详解 滑动编辑 headerView

    转自:http://blog.csdn.net/reylen/article/details/8505960 self.dataArray = [[[NSMutableArray alloc]init ...

  4. tableview 详解I

    在开发iphone的应用时基本上都要用到UITableView,这里讲解一下UITableView的使用方法及代理的调用情况 UITableView使用详解 - (void)viewDidLoad { ...

  5. iPhone应用开发 UITableView学习点滴详解

    iPhone应用开发 UITableView学习点滴详解是本文要介绍的内容,内容不多,主要是以代码实现UITableView的学习点滴,我们来看内容. -.建立 UITableView DataTab ...

  6. UITableView详解(1)

    一,UITableView控件使用必备,红色部分是易错点和难点 首先创建一个项目,要使用UITableView就需要实现协议<UITableViewDataSource>,数据源协议主要完 ...

  7. UITableView 详解 ()

    (原本取至D了个L微信公众号) UITableView 详解 一.建立 UITableView DataTable = [[UITableView alloc] initWithFrame:CGRec ...

  8. XML解析之SAX详解

    XML解析之SAX详解 本文属于作者原创 http://www.cnblogs.com/ldnh/ XML解析的五个步骤 1.打开文档 (void)parserDidStartDocument:(NS ...

  9. IOS 手势详解

    在IOS中手势可以让用户有很好的体验,因此我们有必要去了解一下手势. (在设置手势是有很多值得注意的地方) *是需要设置为Yes的点击无法响应* *要把手势添加到所需点击的View,否则无法响应* 手 ...

随机推荐

  1. mysql查询一天,查询一周,查询一个月的数据【转】

    转自:http://www.cnblogs.com/likwo/archive/2010/04/16/1713282.html 查询一天: select * from table where to_d ...

  2. .NET DataTable转化为json格式

    标准的json用“分隔,不用' public static string DataSetToJson(DataTable dt) {        string json = string.Empty ...

  3. Android Studio 1.0.2 设置内存大小

    http://www.linuxidc.com/Linux/2015-04/116457.htm Android studio 1.0.2默认最大内存是750M,这样跑起来非常的卡,难以忍受,机器又不 ...

  4. 王灏:光音网络致力打造Wi-Fi大生态圈

    光音网络,做的是本地网络综合服务.在中国,想把互联网做到覆盖延伸范围之外的最后100米,光音网络是当中一家,也是最坚持的一家.为千万家本地生活商户提供帮助,为数亿本地用户提供最佳的本地网络体验,这是光 ...

  5. [Webpack 2] Polyfill Promises for Webpack 2

    If you're going to use code splitting with Webpack 2, you'll need to make sure the browser has suppo ...

  6. cf 85 E. Petya and Spiders

    http://codeforces.com/contest/112/problem/E 轮廓线dp.每一个格子中的蜘蛛选一个去向.终于,使每一个蜘蛛都有一个去向,同一时候保证有蜘蛛的格子最少.须要用4 ...

  7. Android SDK无法更新问题解决

    1.在SDK Manager下Tools->Options打开了SDK Manager的Settings,选中“Force https://… sources to be fetched usi ...

  8. Android Studio: 我解决的DEX出错。

    今天开始使用了Android Studio.感觉很方便,很强大.因为它还集成了SVN,GIT等版本管理工具. 由于工程在CheckOut下来后想直接在终端上运行,在引入外部jar包之后开始运行啦,结果 ...

  9. Effective C++ 笔记一 让自己习惯C++

    条款01:视C++为一个语言联邦 C++是个多重范型编程语言,一个同时支持面向过程形式.面向对象形式.函数形式.泛型形式.元编程形式的寓言. 将C++视为几个子语言: 传统C:区块.语句.预处理器.内 ...

  10. phpcms 换域名

    修改/caches/configs/system.php里面所有和域名有关的,把以前的老域名修改为新域名就可以了. 进行后台设置->站点管理   对相应的站点的域名进行修改. 更新系统缓存.点击 ...