iOS开发 自定义tableView样式(使用代码/使用Interface Builder)、分组显示、给TableView增加索引、给TableView增加SearchBar

1、使用代码

自定义tableView样式有两种方法,一种是用代码写cell的subView,另一种是导入nib文件(就是用Interface Builder设计),这篇笔记记录的是代码的方法.
1、新建一个Single View Application 项目,如前文,只选Use Automatic Reference Counting.
2、打开PDViewController.xib,拖进一个Table View,选中Table View,打开Connections inspector,拖动delegate和dataSource右边的小圆到File’s Owner.
3、新建文件,选Cocoa Touch—-Objective-C class,输入类名,我这是MyCell,Subclass of UItableViewCell.生成MyCell.h和MyCell.m两文件。
MyCell.h:
[cpp]  view plain copy
  1. #import <UIKit/UIKit.h>  
  2.    
  3. @interface MyCell : UITableViewCell  
  4. @property (copy,nonatomic) NSString *name;  
  5. @property (copy,nonatomic) NSString *color;  
  6. @end  

MyCell.m:
[cpp]  view plain copy
  1. #import "MyCell.h"  
  2. #define kNameTag 1  
  3. #define kColorTag 2  
  4. @implementation MyCell  
  5. @synthesize name=_name,color=_color;  
  6.    
  7. - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier  
  8. {  
  9.     self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];  
  10.     if (self) {  
  11.         // Initialization code  
  12.         CGRect nameLableRect=CGRectMake(0, 5, 100, 15);  
  13.         //定义一个距形,位置0,5,宽100高15,就是绝对定位  
  14.         UILabel *nameLable=[[UILabel alloc] initWithFrame:nameLableRect];  
  15.         //在距形定义的位置实例化一个UILable对象  
  16.         nameLable.tag=kNameTag;  
  17.         [self.contentView addSubview:nameLable];  
  18.    
  19.    
  20.         CGRect colorLableRect=CGRectMake(0, 30, 100, 15);  
  21.         //定义一个距形,距离上面的nameLable 10  
  22.         UILabel *colorLable=[[UILabel alloc] initWithFrame:colorLableRect];  
  23.         //在距形定义的位置实例化一个UILable对象  
  24.         colorLable.tag=kColorTag;  
  25.         [self.contentView addSubview:colorLable];  
  26.    
  27.    
  28.     }  
  29.     return self;  
  30. }  
  31.    
  32. - (void)setSelected:(BOOL)selected animated:(BOOL)animated  
  33. {  
  34.     [super setSelected:selected animated:animated];  
  35.    
  36.     // Configure the view for the selected state  
  37. }  
  38. //自己写name和color的setter方法  
  39. -(void)setName:(NSString *)name  
  40. {  
  41.     if(![name isEqualToString:_name])  
  42.     {  
  43.         _name=[name copy];  
  44.         UILabel * nameLable=(UILabel *)[self.contentView viewWithTag:kNameTag];  
  45.         //通过viewWithTag方法得到UILable  
  46.         nameLable.text=_name;  
  47.    
  48.     }  
  49. }  
  50. -(void)setColor:(NSString *)color  
  51. {  
  52.     if(![color isEqualToString:_color])  
  53.     {  
  54.         _color=[color copy];  
  55.         UILabel * colorLable=(UILabel *)[self.contentView viewWithTag:kColorTag];  
  56.         colorLable.text=_color;  
  57.    
  58.     }  
  59. }  
  60.    
  61.    
  62. @end  

PDViewControllor.h:
[cpp]  view plain copy
  1. #import <UIKit/UIKit.h>  
  2.    
  3. @interface PDViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>  
  4. //简单起见,不再定义数据,每行数据都一样  
  5. @end  

PDViewController.m
[cpp]  view plain copy
  1. #import "PDViewController.h"  
  2. #import "MyCell.h"  
  3. @implementation PDViewController  
  4.    
  5. - (void)didReceiveMemoryWarning  
  6. {  
  7.     [super didReceiveMemoryWarning];  
  8.     // Release any cached data, images, etc that aren't in use.  
  9. }  
  10.    
  11. #pragma mark - View lifecycle  
  12.    
  13. - (void)viewDidLoad  
  14. {  
  15.     [super viewDidLoad];  
  16.     // Do any additional setup after loading the view, typically from a nib.  
  17. }  
  18.    
  19. - (void)viewDidUnload  
  20. {  
  21.     [super viewDidUnload];  
  22.     // Release any retained subviews of the main view.  
  23.     // e.g. self.myOutlet = nil;  
  24. }  
  25.    
  26. - (void)viewWillAppear:(BOOL)animated  
  27. {  
  28.     [super viewWillAppear:animated];  
  29. }  
  30.    
  31. - (void)viewDidAppear:(BOOL)animated  
  32. {  
  33.     [super viewDidAppear:animated];  
  34. }  
  35.    
  36. - (void)viewWillDisappear:(BOOL)animated  
  37. {  
  38.     [super viewWillDisappear:animated];  
  39. }  
  40.    
  41. - (void)viewDidDisappear:(BOOL)animated  
  42. {  
  43.     [super viewDidDisappear:animated];  
  44. }  
  45.    
  46. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
  47. {  
  48.     // Return YES for supported orientations  
  49.     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);  
  50. }  
  51. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
  52. {  
  53.     return 100;  
  54. }  
  55. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
  56. {  
  57.     static NSString * tableIdentifier=@"Custom table";  
  58.     MyCell *cell=[tableView dequeueReusableCellWithIdentifier:tableIdentifier];  
  59.     if(cell==nil)  
  60.     {  
  61.         cell=[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableIdentifier];  
  62.    
  63.     }  
  64.     cell.name=@"标题";  
  65.     cell.color=@"颜色";  
  66.     //不再定义数据,每行都一样  
  67.     return cell;  
  68. }  
  69. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  
  70. {  
  71.     return 60;  
  72. }  
  73.    
  74. @end  

转自http://www.pocketdigi.com/20120227/678.html

2、使用Interface Builder

前面说到用代码写TableViewCell的样式( ),但代码必竟没有Interface Builder来得方便,今天就介绍使用Interface Builder编辑NIB文件来实现自定义样式。
前面两步与用代码相同,即:
1、新建一个Single View Application 项目,如前文,只选Use Automatic Reference Counting.
2、打开PDViewController.xib,拖进一个Table View,选中Table View,打开Connections inspector,拖动delegate和dataSource右边的小圆到File’s Owner.
第3步,也是写一个继承自UItableViewCell的类(我这取名NIBCell),但内容稍有不同。
NIBCell.h:
[cpp]  view plain copy
  1. #import <UIKit/UIKit.h>  
  2.    
  3. @interface NIBCell : UITableViewCell  
  4.    
  5. @property (strong, nonatomic) IBOutlet UIImageView *thumbView;  
  6. @property (strong, nonatomic) IBOutlet UILabel *titleView;  
  7. //两个outlet与NIB文件中的控件连接  
  8. @property (copy,nonatomic)  NSString * title;  
  9. @property (strong,nonatomic) UIImage * thumb;  
  10. //两个属性分别用于设置上面两个outlet的属性  
  11. @end  

NIBCell.m
[cpp]  view plain copy
  1. #import "NIBCell.h"  
  2.    
  3. @implementation NIBCell  
  4. @synthesize thumbView = _thumbView;  
  5. @synthesize titleView = _titleView;  
  6. @synthesize title=_title,thumb=_thumb;  
  7.    
  8. /* 
  9.  因为样式是在nib文件中定义的,所以不再需要 
  10.  - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 方法 
  11.  */  
  12.    
  13. - (void)setSelected:(BOOL)selected animated:(BOOL)animated  
  14. {  
  15.     [super setSelected:selected animated:animated];  
  16.    
  17.     // Configure the view for the selected state  
  18. }  
  19.    
  20.    
  21. -(void)setTitle:(NSString *)title  
  22. {//覆盖默认生成的setter,但有outlet,不再需要content的viewWithTag方法来取得View  
  23.     if(![self.title isEqualToString:title])  
  24.     {  
  25.         _title=title;  
  26.         _titleView.text=_title;  
  27.     }  
  28.    
  29. }  
  30. -(void)setThumb:(UIImage *)thumb  
  31. {  
  32.     if(![self.thumb isEqual:thumb])  
  33.     {  
  34.         _thumb=thumb;  
  35.         [_thumbView setImage:_thumb];  
  36.     }  
  37. }  
  38.    
  39. @end  

第四步,新建文件,IOS–User Interface–Empty,我这取名TableViewCell.xib
5、单击TableViewCell.xib以便用Interface Builder打开编辑(这时是空的),从控件库里找到Table View Cell,拖进Interface Builder,再拖进一个UILable,和一个UIImage View用于显示一段文字和图片(与前面NIBCell类中的定义相符)
6、选中整个Table View Cell,打开Identity Inspector,把Class改为NIBCell。
7、打开Connections Inspector,找到两个Outlet,thumbView和titleView(我们在NIBCell中定义的),将其右边的小圆圈拖动到Interface Builder里相应的UIImage View和 UILable控件上,建立连接。
8、PDViewController代码:
PDViewController.h
[cpp]  view plain copy
  1. #import <UIKit/UIKit.h>  
  2.    
  3. @interface PDViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>  
  4. //与前面相同,为了简便,不定义用于存储每行信息的数组  
  5. @end  

PDViewController.m
[cpp]  view plain copy
  1. #import "PDViewController.h"  
  2. #import "NIBCell.h"  
  3.    
  4. @implementation PDViewController  
  5.    
  6. - (void)didReceiveMemoryWarning  
  7. {  
  8.     [super didReceiveMemoryWarning];  
  9.     // Release any cached data, images, etc that aren't in use.  
  10. }  
  11.    
  12. #pragma mark - View lifecycle  
  13.    
  14. - (void)viewDidLoad  
  15. {  
  16.     [super viewDidLoad];  
  17.     // Do any additional setup after loading the view, typically from a nib.  
  18. }  
  19.    
  20. - (void)viewDidUnload  
  21. {  
  22.     [super viewDidUnload];  
  23.    
  24.     // Release any retained subviews of the main view.  
  25.     // e.g. self.myOutlet = nil;  
  26. }  
  27.    
  28. - (void)viewWillAppear:(BOOL)animated  
  29. {  
  30.     [super viewWillAppear:animated];  
  31. }  
  32.    
  33. - (void)viewDidAppear:(BOOL)animated  
  34. {  
  35.     [super viewDidAppear:animated];  
  36. }  
  37.    
  38. - (void)viewWillDisappear:(BOOL)animated  
  39. {  
  40.     [super viewWillDisappear:animated];  
  41. }  
  42.    
  43. - (void)viewDidDisappear:(BOOL)animated  
  44. {  
  45.     [super viewDidDisappear:animated];  
  46. }  
  47.    
  48. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
  49. {  
  50.     // Return YES for supported orientations  
  51.     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);  
  52. }  
  53. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
  54. {  
  55. //返回行数  
  56.     return 100;  
  57. }  
  58. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
  59. {  
  60.     static NSString * tableIdentifier=@"CellFromNib";  
  61.     static BOOL nibsRegistered=NO;  
  62.     if(!nibsRegistered)  
  63.     {//第一次运行时注册nib文件,文件名不需要扩展名  
  64.         UINib *nib=[UINib nibWithNibName:@"TableViewCell" bundle:nil];  
  65.         [tableView registerNib:nib forCellReuseIdentifier:tableIdentifier];  
  66.         nibsRegistered=YES;  
  67.     }  
  68.     NIBCell *cell=[tableView dequeueReusableCellWithIdentifier:tableIdentifier];  
  69.     NSUInteger rowNumber=[indexPath row];  
  70.     NSString *title=[[NSString alloc] initWithFormat:@"%d",rowNumber];  
  71.     cell.title=title;  
  72.     UIImage *image=[UIImage imageNamed:@"57"];  
  73.     cell.thumb=image;  
  74.     //显示行号,和一张固定的图片,图片同样不需要扩展名  
  75.     return cell;  
  76. }  
  77. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  
  78. {  
  79.     //返回行高  
  80.     return 100;  
  81. }  
  82.    
  83. @end  

转自http://www.pocketdigi.com/20120319/713.html

3、分组显示TableView

IOS中可以分组显示TableView,效果类似于“设置”程序。
新建项目的步骤不再重复,请参考前文。有一点区别在于,需要把Table View的Style属性设置成Grouped(在Attributes Inspector中)。这里需要先写个plist文件,用于存储需要显示的数据。
plist文件本身对应NSDictionary数据类型,也就是说plist文件,其实是个字典。本例plist文件名为sortednames.plist,内容及结构如下图:

两个字符串数组,键名分别为A,B,当然,你也可以在程序中用代码写NSDictionary,这样就不需要sortednames.plist。
PDViewController.h
[cpp]  view plain copy
  1. #import <UIKit/UIKit.h>  
  2.    
  3. @interface PDViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>  
  4. @property (strong,nonatomic) NSDictionary *names;  
  5. @property(strong,nonatomic)NSArray *keys;  
  6.    
  7. @end  

PDAppDelegate.m
[cpp]  view plain copy
  1. #import "PDViewController.h"  
  2. #import "NIBCell.h"  
  3.    
  4. @implementation PDViewController  
  5. @synthesize names=_names,keys=_keys;  
  6.    
  7. - (void)didReceiveMemoryWarning  
  8. {  
  9.     [super didReceiveMemoryWarning];  
  10.     // Release any cached data, images, etc that aren't in use.  
  11. }  
  12.    
  13. #pragma mark - View lifecycle  
  14.    
  15. - (void)viewDidLoad  
  16. {  
  17.     [super viewDidLoad];  
  18.     // Do any additional setup after loading the view, typically from a nib.  
  19.     NSString *path=[[NSBundle mainBundle] pathForResource:@"sortednames" ofType:@"plist"];  
  20.     //取得sortednames.plist绝对路径  
  21.     //sortednames.plist本身是一个NSDictionary,以键-值的形式存储字符串数组  
  22.    
  23.     NSDictionary *dict=[[NSDictionary alloc] initWithContentsOfFile:path];  
  24.     //转换成NSDictionary对象  
  25.     self.names=dict;  
  26.     NSArray *array=[[_names allKeys] sortedArrayUsingSelector:@selector(compare:)];  
  27.     //取得字典中所有的key,使用compare方法(必须是返回NSComparisonResult的方法)排序  
  28.     //这里取得的key,对应的值是Array  
  29.     _keys=array;  
  30. }  
  31.    
  32. - (void)viewDidUnload  
  33. {  
  34.     [super viewDidUnload];  
  35.     self.names=nil;  
  36.     self.keys=nil;  
  37.     // Release any retained subviews of the main view.  
  38.     // e.g. self.myOutlet = nil;  
  39. }  
  40.    
  41. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
  42. {  
  43.     // Return YES for supported orientations  
  44.     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);  
  45. }  
  46. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView  
  47. {  
  48.     //返回分组数量,即Array的数量  
  49.     return [_keys count];  
  50.    
  51. }  
  52. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
  53. {  
  54.     //返回第section个分组的行数  
  55.     NSString *key=[_keys objectAtIndex:section];  
  56.     //取得key  
  57.     NSArray *nameSection=[_names objectForKey:key];  
  58.     //根据key,取得Array  
  59.     return [nameSection count];  
  60.     //返回Array的大小  
  61.    
  62. }  
  63. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
  64. {  
  65.    
  66.     NSUInteger section=[indexPath section];  
  67.     //分组号  
  68.     NSUInteger rowNumber=[indexPath row];  
  69.     //行号  
  70.     //即返回第section组,rowNumber行的UITableViewCell  
  71.    
  72.     NSString *key=[_keys objectAtIndex:section];  
  73.     //取得第section组array的key  
  74.     NSArray *nameSection=[_names objectForKey:key];  
  75.     //通过key,取得Array  
  76.    
  77.     static NSString * tableIdentifier=@"CellFromNib";  
  78.    
  79.     UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:tableIdentifier];  
  80.     if(cell==nil)  
  81.     {  
  82.         cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableIdentifier];  
  83.    
  84.     }  
  85.     cell.textLabel.text=[nameSection objectAtIndex:rowNumber];   
  86.     //从数组中读取字符串,设置text  
  87.     return cell;  
  88. }  
  89.    
  90. @end  
转自http://www.pocketdigi.com/20120320/715.html

4、给TableView增加索引

当TableView显示的数据很多的时间,可以给其添加索引,添加索引后,在TableView的右侧会显示索引的键,手指滑动这里,就可以快速切换到该键对应的数据(好像联系人就是这样的,很久没用iPhone了,不敢肯定,我只有iPod,没联系人).
具体实现代码只需在前文 的基础上修改。
打开PDViewController.m,增加一个selector:
[cpp]  view plain copy
  1. -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView  
  2. {  
  3.     return _keys;  
  4.     //通过key来索引  
  5. }  

上面的这个selector是在UITableViewDataSource中声明的,我们已经支持了这个协议。
Table View的Style属性,不管是默认的Plain还是前文中修改的Grouped都可以。

5、给TableView增加SearchBar


可以根据输入的关键字,在TableView中显示符合的数据。
图中分组显示和索引效果,前面的博文已经记录,不再赘述。下面的例子是基于前文的基础上修改的,所以文件名啥的,请参考前文。
第一步是在TableView上方添加一个Search Bar,这里有一点需要注意,必须先把TableView拖下来,留下空间放Search Bar,不要在Table View占满屏幕的情况下把Search Bar拖到Table View顶部。区别在于,使用后面的方法,Search Bar是作为Table View的Header部分添加的,而前面的方法,Search Bar是独立的。在添加索引功能时,如果作为Table View的Header添加,右侧的索引会遮住Search Bar的右边部分。Search Bar几个常用属性:
Placeholder是提示,就是hint属性,Corretion是自动修正,一般设为NO,即不修正,Show Cancel Button是显示取消按钮,我这里勾选。选中Search Bar的情况下切换到Connections Inspector面板,delegate与File’s Owner建立连接(我们会在ViewController中支持UISearchBarDelegate协议)。与前面几篇文章的例子相同,ViewController文件名为PDViewController.h和PDViewController.m。
第二步,添加Table View和Search Bar的Outlet.按住Control键,分别拖动Table View和Search Bar到PDViewController.h,添加Outlet
第三步,就是PDViewController代码:
PDViewController.h:
[cpp]  view plain copy
  1. #import <UIKit/UIKit.h>  
  2.    
  3. @interface PDViewController : UIViewController<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>  
  4. @property (strong,nonatomic) NSDictionary *names;  
  5. @property (strong,nonatomic) NSMutableDictionary *mutableNames;  
  6. @property (strong,nonatomic)NSMutableArray *mutableKeys;  
  7. //可变字典和可变数组,用于存储显示的数据,而不可变的字典用于存储从文件中读取的数据  
  8. @property (strong, nonatomic) IBOutlet UITableView *table;  
  9. @property (strong, nonatomic) IBOutlet UISearchBar *search;  
  10. -(void)resetSearch;  
  11. //重置搜索,即恢复到没有输入关键字的状态  
  12. -(void)handleSearchForTerm:(NSString *)searchTerm;  
  13. //处理搜索,即把不包含searchTerm的值从可变数组中删除  
  14.    
  15. @end  

PDViewController.m:
[cpp]  view plain copy
  1. #import "PDViewController.h"  
  2. #import "NSDictionary+MutableDeepCopy.h"  
  3.    
  4. @implementation PDViewController  
  5. @synthesize names=_names;  
  6. @synthesize mutableKeys=_mutableKeys;  
  7. @synthesize table = _table;  
  8. @synthesize search = _search;  
  9. @synthesize mutableNames=_mutableNames;  
  10. - (void)didReceiveMemoryWarning  
  11. {  
  12.     [super didReceiveMemoryWarning];  
  13.     // Release any cached data, images, etc that aren't in use.  
  14. }  
  15.    
  16. #pragma mark - View lifecycle  
  17.    
  18. - (void)viewDidLoad  
  19. {  
  20.     [super viewDidLoad];  
  21.     // Do any additional setup after loading the view, typically from a nib.  
  22.     NSString *path=[[NSBundle mainBundle] pathForResource:@"sortednames" ofType:@"plist"];  
  23.     //取得sortednames.plist绝对路径  
  24.     //sortednames.plist本身是一个NSDictionary,以键-值的形式存储字符串数组  
  25.    
  26.     NSDictionary *dict=[[NSDictionary alloc] initWithContentsOfFile:path];  
  27.     //转换成NSDictionary对象  
  28.     self.names=dict;  
  29.    
  30.     [self resetSearch];  
  31.     //重置  
  32.     [_table reloadData];  
  33.     //重新载入数据  
  34.    
  35. }  
  36.    
  37. - (void)viewDidUnload  
  38. {  
  39.     [self setTable:nil];  
  40.     [self setSearch:nil];  
  41.     [super viewDidUnload];  
  42.     self.names=nil;  
  43.     self.mutableKeys=nil;  
  44.     self.mutableNames=nil;  
  45.     // Release any retained subviews of the main view.  
  46.     // e.g. self.myOutlet = nil;  
  47. }  
  48.    
  49. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
  50. {  
  51.     // Return YES for supported orientations  
  52.     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);  
  53. }  
  54. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView  
  55. {  
  56.     //返回分组数量,即Array的数量  
  57.     return [_mutableKeys count];  
  58.     //  
  59.    
  60. }  
  61. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
  62. {  
  63.    
  64.     if ([_mutableKeys count]==0) {  
  65.         return 0;  
  66.     }  
  67.     NSString *key=[_mutableKeys objectAtIndex:section];  
  68.     NSArray *nameSection=[_mutableNames objectForKey:key];  
  69.     return [nameSection count];  
  70.     //返回Array的大小  
  71.    
  72. }  
  73. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
  74. {  
  75.    
  76.     NSUInteger section=[indexPath section];  
  77.     //分组号  
  78.     NSUInteger rowNumber=[indexPath row];  
  79.     //行号  
  80.     //即返回第section组,rowNumber行的UITableViewCell  
  81.    
  82.     NSString *key=[_mutableKeys objectAtIndex:section];  
  83.     //取得第section组array的key  
  84.     NSArray *nameSection=[_mutableNames objectForKey:key];  
  85.     //通过key,取得Array  
  86.    
  87.     static NSString * tableIdentifier=@"CellFromNib";  
  88.    
  89.     UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:tableIdentifier];  
  90.     if(cell==nil)  
  91.     {  
  92.         cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableIdentifier];  
  93.    
  94.     }  
  95.     cell.textLabel.text=[nameSection objectAtIndex:rowNumber];   
  96.     //从数组中读取字符串,设置text  
  97.     return cell;  
  98. }  
  99. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section  
  100. {  
  101.     if ([_mutableKeys count]==0) {  
  102.         return 0;  
  103.     }  
  104.     NSString *key=[_mutableKeys objectAtIndex:section];  
  105.     return key;  
  106. }  
  107. -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView  
  108. {  
  109.     return _mutableKeys;  
  110.     //通过key来索引  
  111. }  
  112. -(void)resetSearch  
  113. {//重置搜索  
  114.     _mutableNames=[_names mutableDeepCopy];  
  115.     //使用mutableDeepCopy方法深复制  
  116.     NSMutableArray *keyarr=[NSMutableArray new];  
  117.     [keyarr addObjectsFromArray:[[_names allKeys] sortedArrayUsingSelector:@selector(compare:)]];  
  118.     //读取键,排序后存放可变数组  
  119.     _mutableKeys=keyarr;  
  120.    
  121. }  
  122. -(void)handleSearchForTerm:(NSString *)searchTerm  
  123. {//处理搜索  
  124.     NSMutableArray *sectionToRemove=[NSMutableArray new];  
  125.     //分组待删除列表  
  126.     [self resetSearch];  
  127.     //先重置  
  128.     for(NSString *key in _mutableKeys)  
  129.     {//循环读取所有的数组  
  130.         NSMutableArray *array=[_mutableNames valueForKey:key];  
  131.         NSMutableArray *toRemove=[NSMutableArray new];  
  132.         //待删除列表  
  133.         for(NSString *name in array)  
  134.         {//数组内的元素循环对比  
  135.             if([name rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location==NSNotFound)  
  136.             {  
  137.                 //rangeOfString方法是返回NSRange对象(包含位置索引和长度信息)  
  138.                 //NSCaseInsensitiveSearch是忽略大小写  
  139.                 //这里的代码会在name中找不到searchTerm时执行  
  140.                 [toRemove addObject:name];  
  141.                 //找不到,把name添加到待删除列表  
  142.             }  
  143.         }  
  144.         if ([array count]==[toRemove count]) {  
  145.             [sectionToRemove addObject:key];  
  146.         //如果待删除的总数和数组元素总数相同,把该分组的key加入待删除列表,即不显示该分组  
  147.         }  
  148.         [array removeObjectsInArray:toRemove];  
  149.         //删除数组待删除元素  
  150.     }  
  151.     [_mutableKeys removeObjectsInArray:sectionToRemove];  
  152.     //能过待删除的key数组删除数组  
  153.     [_table reloadData];  
  154.     //重载数据  
  155.    
  156. }  
  157. -(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath  
  158. {//TableView的项被选择前触发  
  159.     [_search resignFirstResponder];  
  160.     //搜索条释放焦点,隐藏软键盘  
  161.     return indexPath;  
  162. }  
  163. -(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar  
  164. {//按软键盘右下角的搜索按钮时触发  
  165.     NSString *searchTerm=[searchBar text];  
  166.     //读取被输入的关键字  
  167.     [self handleSearchForTerm:searchTerm];  
  168.     //根据关键字,进行处理  
  169.     [_search resignFirstResponder];  
  170.     //隐藏软键盘  
  171.    
  172. }  
  173. -(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText  
  174. {//搜索条输入文字修改时触发  
  175.     if([searchText length]==0)  
  176.     {//如果无文字输入  
  177.         [self resetSearch];  
  178.         [_table reloadData];  
  179.         return;   
  180.     }  
  181.    
  182.     [self handleSearchForTerm:searchText];  
  183.     //有文字输入就把关键字传给handleSearchForTerm处理  
  184. }  
  185. -(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar  
  186. {//取消按钮被按下时触发  
  187.     [self resetSearch];  
  188.     //重置  
  189.     searchBar.text=@"";  
  190.     //输入框清空  
  191.     [_table reloadData];  
  192.     [_search resignFirstResponder];  
  193.     //重新载入数据,隐藏软键盘  
  194.    
  195. }  
  196.    
  197.    
  198. @end  

mutableDeepCopy深复制的方法在NSDictionary+MutableDeepCopy定义,参考 iOS/Objective-C开发 字典NSDictionary的深复制(使用category)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值