`
yidongkaifa
  • 浏览: 4059805 次
文章分类
社区版块
存档分类
最新评论

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:
  1. #import<UIKit/UIKit.h>
  2. @interfaceMyCell:UITableViewCell
  3. @property(copy,nonatomic)NSString*name;
  4. @property(copy,nonatomic)NSString*color;
  5. @end

MyCell.m:
  1. #import"MyCell.h"
  2. #definekNameTag1
  3. #definekColorTag2
  4. @implementationMyCell
  5. @synthesizename=_name,color=_color;
  6. -(id)initWithStyle:(UITableViewCellStyle)stylereuseIdentifier:(NSString*)reuseIdentifier
  7. {
  8. self=[superinitWithStyle:stylereuseIdentifier:reuseIdentifier];
  9. if(self){
  10. //Initializationcode
  11. CGRectnameLableRect=CGRectMake(0,5,100,15);
  12. //定义一个距形,位置0,5,宽100高15,就是绝对定位
  13. UILabel*nameLable=[[UILabelalloc]initWithFrame:nameLableRect];
  14. //在距形定义的位置实例化一个UILable对象
  15. nameLable.tag=kNameTag;
  16. [self.contentViewaddSubview:nameLable];
  17. CGRectcolorLableRect=CGRectMake(0,30,100,15);
  18. //定义一个距形,距离上面的nameLable10
  19. UILabel*colorLable=[[UILabelalloc]initWithFrame:colorLableRect];
  20. //在距形定义的位置实例化一个UILable对象
  21. colorLable.tag=kColorTag;
  22. [self.contentViewaddSubview:colorLable];
  23. }
  24. returnself;
  25. }
  26. -(void)setSelected:(BOOL)selectedanimated:(BOOL)animated
  27. {
  28. [supersetSelected:selectedanimated:animated];
  29. //Configuretheviewfortheselectedstate
  30. }
  31. //自己写name和color的setter方法
  32. -(void)setName:(NSString*)name
  33. {
  34. if(![nameisEqualToString:_name])
  35. {
  36. _name=[namecopy];
  37. UILabel*nameLable=(UILabel*)[self.contentViewviewWithTag:kNameTag];
  38. //通过viewWithTag方法得到UILable
  39. nameLable.text=_name;
  40. }
  41. }
  42. -(void)setColor:(NSString*)color
  43. {
  44. if(![colorisEqualToString:_color])
  45. {
  46. _color=[colorcopy];
  47. UILabel*colorLable=(UILabel*)[self.contentViewviewWithTag:kColorTag];
  48. colorLable.text=_color;
  49. }
  50. }
  51. @end

PDViewControllor.h:
  1. #import<UIKit/UIKit.h>
  2. @interfacePDViewController:UIViewController<UITableViewDelegate,UITableViewDataSource>
  3. //简单起见,不再定义数据,每行数据都一样
  4. @end

PDViewController.m
  1. #import"PDViewController.h"
  2. #import"MyCell.h"
  3. @implementationPDViewController
  4. -(void)didReceiveMemoryWarning
  5. {
  6. [superdidReceiveMemoryWarning];
  7. //Releaseanycacheddata,images,etcthataren'tinuse.
  8. }
  9. #pragmamark-Viewlifecycle
  10. -(void)viewDidLoad
  11. {
  12. [superviewDidLoad];
  13. //Doanyadditionalsetupafterloadingtheview,typicallyfromanib.
  14. }
  15. -(void)viewDidUnload
  16. {
  17. [superviewDidUnload];
  18. //Releaseanyretainedsubviewsofthemainview.
  19. //e.g.self.myOutlet=nil;
  20. }
  21. -(void)viewWillAppear:(BOOL)animated
  22. {
  23. [superviewWillAppear:animated];
  24. }
  25. -(void)viewDidAppear:(BOOL)animated
  26. {
  27. [superviewDidAppear:animated];
  28. }
  29. -(void)viewWillDisappear:(BOOL)animated
  30. {
  31. [superviewWillDisappear:animated];
  32. }
  33. -(void)viewDidDisappear:(BOOL)animated
  34. {
  35. [superviewDidDisappear:animated];
  36. }
  37. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
  38. {
  39. //ReturnYESforsupportedorientations
  40. return(interfaceOrientation!=UIInterfaceOrientationPortraitUpsideDown);
  41. }
  42. -(NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section
  43. {
  44. return100;
  45. }
  46. -(UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath
  47. {
  48. staticNSString*tableIdentifier=@"Customtable";
  49. MyCell*cell=[tableViewdequeueReusableCellWithIdentifier:tableIdentifier];
  50. if(cell==nil)
  51. {
  52. cell=[[MyCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:tableIdentifier];
  53. }
  54. cell.name=@"标题";
  55. cell.color=@"颜色";
  56. //不再定义数据,每行都一样
  57. returncell;
  58. }
  59. -(CGFloat)tableView:(UITableView*)tableViewheightForRowAtIndexPath:(NSIndexPath*)indexPath
  60. {
  61. return60;
  62. }
  63. @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:
  1. #import<UIKit/UIKit.h>
  2. @interfaceNIBCell:UITableViewCell
  3. @property(strong,nonatomic)IBOutletUIImageView*thumbView;
  4. @property(strong,nonatomic)IBOutletUILabel*titleView;
  5. //两个outlet与NIB文件中的控件连接
  6. @property(copy,nonatomic)NSString*title;
  7. @property(strong,nonatomic)UIImage*thumb;
  8. //两个属性分别用于设置上面两个outlet的属性
  9. @end

NIBCell.m
  1. #import"NIBCell.h"
  2. @implementationNIBCell
  3. @synthesizethumbView=_thumbView;
  4. @synthesizetitleView=_titleView;
  5. @synthesizetitle=_title,thumb=_thumb;
  6. /*
  7. 因为样式是在nib文件中定义的,所以不再需要
  8. -(id)initWithStyle:(UITableViewCellStyle)stylereuseIdentifier:(NSString*)reuseIdentifier方法
  9. */
  10. -(void)setSelected:(BOOL)selectedanimated:(BOOL)animated
  11. {
  12. [supersetSelected:selectedanimated:animated];
  13. //Configuretheviewfortheselectedstate
  14. }
  15. -(void)setTitle:(NSString*)title
  16. {//覆盖默认生成的setter,但有outlet,不再需要content的viewWithTag方法来取得View
  17. if(![self.titleisEqualToString:title])
  18. {
  19. _title=title;
  20. _titleView.text=_title;
  21. }
  22. }
  23. -(void)setThumb:(UIImage*)thumb
  24. {
  25. if(![self.thumbisEqual:thumb])
  26. {
  27. _thumb=thumb;
  28. [_thumbViewsetImage:_thumb];
  29. }
  30. }
  31. @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
  1. #import<UIKit/UIKit.h>
  2. @interfacePDViewController:UIViewController<UITableViewDelegate,UITableViewDataSource>
  3. //与前面相同,为了简便,不定义用于存储每行信息的数组
  4. @end

PDViewController.m
  1. #import"PDViewController.h"
  2. #import"NIBCell.h"
  3. @implementationPDViewController
  4. -(void)didReceiveMemoryWarning
  5. {
  6. [superdidReceiveMemoryWarning];
  7. //Releaseanycacheddata,images,etcthataren'tinuse.
  8. }
  9. #pragmamark-Viewlifecycle
  10. -(void)viewDidLoad
  11. {
  12. [superviewDidLoad];
  13. //Doanyadditionalsetupafterloadingtheview,typicallyfromanib.
  14. }
  15. -(void)viewDidUnload
  16. {
  17. [superviewDidUnload];
  18. //Releaseanyretainedsubviewsofthemainview.
  19. //e.g.self.myOutlet=nil;
  20. }
  21. -(void)viewWillAppear:(BOOL)animated
  22. {
  23. [superviewWillAppear:animated];
  24. }
  25. -(void)viewDidAppear:(BOOL)animated
  26. {
  27. [superviewDidAppear:animated];
  28. }
  29. -(void)viewWillDisappear:(BOOL)animated
  30. {
  31. [superviewWillDisappear:animated];
  32. }
  33. -(void)viewDidDisappear:(BOOL)animated
  34. {
  35. [superviewDidDisappear:animated];
  36. }
  37. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
  38. {
  39. //ReturnYESforsupportedorientations
  40. return(interfaceOrientation!=UIInterfaceOrientationPortraitUpsideDown);
  41. }
  42. -(NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section
  43. {
  44. //返回行数
  45. return100;
  46. }
  47. -(UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath
  48. {
  49. staticNSString*tableIdentifier=@"CellFromNib";
  50. staticBOOLnibsRegistered=NO;
  51. if(!nibsRegistered)
  52. {//第一次运行时注册nib文件,文件名不需要扩展名
  53. UINib*nib=[UINibnibWithNibName:@"TableViewCell"bundle:nil];
  54. [tableViewregisterNib:nibforCellReuseIdentifier:tableIdentifier];
  55. nibsRegistered=YES;
  56. }
  57. NIBCell*cell=[tableViewdequeueReusableCellWithIdentifier:tableIdentifier];
  58. NSUIntegerrowNumber=[indexPathrow];
  59. NSString*title=[[NSStringalloc]initWithFormat:@"%d",rowNumber];
  60. cell.title=title;
  61. UIImage*image=[UIImageimageNamed:@"57"];
  62. cell.thumb=image;
  63. //显示行号,和一张固定的图片,图片同样不需要扩展名
  64. returncell;
  65. }
  66. -(CGFloat)tableView:(UITableView*)tableViewheightForRowAtIndexPath:(NSIndexPath*)indexPath
  67. {
  68. //返回行高
  69. return100;
  70. }
  71. @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
  1. #import<UIKit/UIKit.h>
  2. @interfacePDViewController:UIViewController<UITableViewDelegate,UITableViewDataSource>
  3. @property(strong,nonatomic)NSDictionary*names;
  4. @property(strong,nonatomic)NSArray*keys;
  5. @end

PDAppDelegate.m
  1. #import"PDViewController.h"
  2. #import"NIBCell.h"
  3. @implementationPDViewController
  4. @synthesizenames=_names,keys=_keys;
  5. -(void)didReceiveMemoryWarning
  6. {
  7. [superdidReceiveMemoryWarning];
  8. //Releaseanycacheddata,images,etcthataren'tinuse.
  9. }
  10. #pragmamark-Viewlifecycle
  11. -(void)viewDidLoad
  12. {
  13. [superviewDidLoad];
  14. //Doanyadditionalsetupafterloadingtheview,typicallyfromanib.
  15. NSString*path=[[NSBundlemainBundle]pathForResource:@"sortednames"ofType:@"plist"];
  16. //取得sortednames.plist绝对路径
  17. //sortednames.plist本身是一个NSDictionary,以键-值的形式存储字符串数组
  18. NSDictionary*dict=[[NSDictionaryalloc]initWithContentsOfFile:path];
  19. //转换成NSDictionary对象
  20. self.names=dict;
  21. NSArray*array=[[_namesallKeys]sortedArrayUsingSelector:@selector(compare:)];
  22. //取得字典中所有的key,使用compare方法(必须是返回NSComparisonResult的方法)排序
  23. //这里取得的key,对应的值是Array
  24. _keys=array;
  25. }
  26. -(void)viewDidUnload
  27. {
  28. [superviewDidUnload];
  29. self.names=nil;
  30. self.keys=nil;
  31. //Releaseanyretainedsubviewsofthemainview.
  32. //e.g.self.myOutlet=nil;
  33. }
  34. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
  35. {
  36. //ReturnYESforsupportedorientations
  37. return(interfaceOrientation!=UIInterfaceOrientationPortraitUpsideDown);
  38. }
  39. -(NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
  40. {
  41. //返回分组数量,即Array的数量
  42. return[_keyscount];
  43. }
  44. -(NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section
  45. {
  46. //返回第section个分组的行数
  47. NSString*key=[_keysobjectAtIndex:section];
  48. //取得key
  49. NSArray*nameSection=[_namesobjectForKey:key];
  50. //根据key,取得Array
  51. return[nameSectioncount];
  52. //返回Array的大小
  53. }
  54. -(UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath
  55. {
  56. NSUIntegersection=[indexPathsection];
  57. //分组号
  58. NSUIntegerrowNumber=[indexPathrow];
  59. //行号
  60. //即返回第section组,rowNumber行的UITableViewCell
  61. NSString*key=[_keysobjectAtIndex:section];
  62. //取得第section组array的key
  63. NSArray*nameSection=[_namesobjectForKey:key];
  64. //通过key,取得Array
  65. staticNSString*tableIdentifier=@"CellFromNib";
  66. UITableViewCell*cell=[tableViewdequeueReusableCellWithIdentifier:tableIdentifier];
  67. if(cell==nil)
  68. {
  69. cell=[[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:tableIdentifier];
  70. }
  71. cell.textLabel.text=[nameSectionobjectAtIndex:rowNumber];
  72. //从数组中读取字符串,设置text
  73. returncell;
  74. }
  75. @end
转自http://www.pocketdigi.com/20120320/715.html

4、给TableView增加索引

当TableView显示的数据很多的时间,可以给其添加索引,添加索引后,在TableView的右侧会显示索引的键,手指滑动这里,就可以快速切换到该键对应的数据(好像联系人就是这样的,很久没用iPhone了,不敢肯定,我只有iPod,没联系人).
具体实现代码只需在前文的基础上修改。
打开PDViewController.m,增加一个selector:
  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:
  1. #import<UIKit/UIKit.h>
  2. @interfacePDViewController:UIViewController<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
  3. @property(strong,nonatomic)NSDictionary*names;
  4. @property(strong,nonatomic)NSMutableDictionary*mutableNames;
  5. @property(strong,nonatomic)NSMutableArray*mutableKeys;
  6. //可变字典和可变数组,用于存储显示的数据,而不可变的字典用于存储从文件中读取的数据
  7. @property(strong,nonatomic)IBOutletUITableView*table;
  8. @property(strong,nonatomic)IBOutletUISearchBar*search;
  9. -(void)resetSearch;
  10. //重置搜索,即恢复到没有输入关键字的状态
  11. -(void)handleSearchForTerm:(NSString*)searchTerm;
  12. //处理搜索,即把不包含searchTerm的值从可变数组中删除
  13. @end

PDViewController.m:
  1. #import"PDViewController.h"
  2. #import"NSDictionary+MutableDeepCopy.h"
  3. @implementationPDViewController
  4. @synthesizenames=_names;
  5. @synthesizemutableKeys=_mutableKeys;
  6. @synthesizetable=_table;
  7. @synthesizesearch=_search;
  8. @synthesizemutableNames=_mutableNames;
  9. -(void)didReceiveMemoryWarning
  10. {
  11. [superdidReceiveMemoryWarning];
  12. //Releaseanycacheddata,images,etcthataren'tinuse.
  13. }
  14. #pragmamark-Viewlifecycle
  15. -(void)viewDidLoad
  16. {
  17. [superviewDidLoad];
  18. //Doanyadditionalsetupafterloadingtheview,typicallyfromanib.
  19. NSString*path=[[NSBundlemainBundle]pathForResource:@"sortednames"ofType:@"plist"];
  20. //取得sortednames.plist绝对路径
  21. //sortednames.plist本身是一个NSDictionary,以键-值的形式存储字符串数组
  22. NSDictionary*dict=[[NSDictionaryalloc]initWithContentsOfFile:path];
  23. //转换成NSDictionary对象
  24. self.names=dict;
  25. [selfresetSearch];
  26. //重置
  27. [_tablereloadData];
  28. //重新载入数据
  29. }
  30. -(void)viewDidUnload
  31. {
  32. [selfsetTable:nil];
  33. [selfsetSearch:nil];
  34. [superviewDidUnload];
  35. self.names=nil;
  36. self.mutableKeys=nil;
  37. self.mutableNames=nil;
  38. //Releaseanyretainedsubviewsofthemainview.
  39. //e.g.self.myOutlet=nil;
  40. }
  41. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
  42. {
  43. //ReturnYESforsupportedorientations
  44. return(interfaceOrientation!=UIInterfaceOrientationPortraitUpsideDown);
  45. }
  46. -(NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
  47. {
  48. //返回分组数量,即Array的数量
  49. return[_mutableKeyscount];
  50. //
  51. }
  52. -(NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section
  53. {
  54. if([_mutableKeyscount]==0){
  55. return0;
  56. }
  57. NSString*key=[_mutableKeysobjectAtIndex:section];
  58. NSArray*nameSection=[_mutableNamesobjectForKey:key];
  59. return[nameSectioncount];
  60. //返回Array的大小
  61. }
  62. -(UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath
  63. {
  64. NSUIntegersection=[indexPathsection];
  65. //分组号
  66. NSUIntegerrowNumber=[indexPathrow];
  67. //行号
  68. //即返回第section组,rowNumber行的UITableViewCell
  69. NSString*key=[_mutableKeysobjectAtIndex:section];
  70. //取得第section组array的key
  71. NSArray*nameSection=[_mutableNamesobjectForKey:key];
  72. //通过key,取得Array
  73. staticNSString*tableIdentifier=@"CellFromNib";
  74. UITableViewCell*cell=[tableViewdequeueReusableCellWithIdentifier:tableIdentifier];
  75. if(cell==nil)
  76. {
  77. cell=[[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:tableIdentifier];
  78. }
  79. cell.textLabel.text=[nameSectionobjectAtIndex:rowNumber];
  80. //从数组中读取字符串,设置text
  81. returncell;
  82. }
  83. -(NSString*)tableView:(UITableView*)tableViewtitleForHeaderInSection:(NSInteger)section
  84. {
  85. if([_mutableKeyscount]==0){
  86. return0;
  87. }
  88. NSString*key=[_mutableKeysobjectAtIndex:section];
  89. returnkey;
  90. }
  91. -(NSArray*)sectionIndexTitlesForTableView:(UITableView*)tableView
  92. {
  93. return_mutableKeys;
  94. //通过key来索引
  95. }
  96. -(void)resetSearch
  97. {//重置搜索
  98. _mutableNames=[_namesmutableDeepCopy];
  99. //使用mutableDeepCopy方法深复制
  100. NSMutableArray*keyarr=[NSMutableArraynew];
  101. [keyarraddObjectsFromArray:[[_namesallKeys]sortedArrayUsingSelector:@selector(compare:)]];
  102. //读取键,排序后存放可变数组
  103. _mutableKeys=keyarr;
  104. }
  105. -(void)handleSearchForTerm:(NSString*)searchTerm
  106. {//处理搜索
  107. NSMutableArray*sectionToRemove=[NSMutableArraynew];
  108. //分组待删除列表
  109. [selfresetSearch];
  110. //先重置
  111. for(NSString*keyin_mutableKeys)
  112. {//循环读取所有的数组
  113. NSMutableArray*array=[_mutableNamesvalueForKey:key];
  114. NSMutableArray*toRemove=[NSMutableArraynew];
  115. //待删除列表
  116. for(NSString*nameinarray)
  117. {//数组内的元素循环对比
  118. if([namerangeOfString:searchTermoptions:NSCaseInsensitiveSearch].location==NSNotFound)
  119. {
  120. //rangeOfString方法是返回NSRange对象(包含位置索引和长度信息)
  121. //NSCaseInsensitiveSearch是忽略大小写
  122. //这里的代码会在name中找不到searchTerm时执行
  123. [toRemoveaddObject:name];
  124. //找不到,把name添加到待删除列表
  125. }
  126. }
  127. if([arraycount]==[toRemovecount]){
  128. [sectionToRemoveaddObject:key];
  129. //如果待删除的总数和数组元素总数相同,把该分组的key加入待删除列表,即不显示该分组
  130. }
  131. [arrayremoveObjectsInArray:toRemove];
  132. //删除数组待删除元素
  133. }
  134. [_mutableKeysremoveObjectsInArray:sectionToRemove];
  135. //能过待删除的key数组删除数组
  136. [_tablereloadData];
  137. //重载数据
  138. }
  139. -(NSIndexPath*)tableView:(UITableView*)tableViewwillSelectRowAtIndexPath:(NSIndexPath*)indexPath
  140. {//TableView的项被选择前触发
  141. [_searchresignFirstResponder];
  142. //搜索条释放焦点,隐藏软键盘
  143. returnindexPath;
  144. }
  145. -(void)searchBarSearchButtonClicked:(UISearchBar*)searchBar
  146. {//按软键盘右下角的搜索按钮时触发
  147. NSString*searchTerm=[searchBartext];
  148. //读取被输入的关键字
  149. [selfhandleSearchForTerm:searchTerm];
  150. //根据关键字,进行处理
  151. [_searchresignFirstResponder];
  152. //隐藏软键盘
  153. }
  154. -(void)searchBar:(UISearchBar*)searchBartextDidChange:(NSString*)searchText
  155. {//搜索条输入文字修改时触发
  156. if([searchTextlength]==0)
  157. {//如果无文字输入
  158. [selfresetSearch];
  159. [_tablereloadData];
  160. return;
  161. }
  162. [selfhandleSearchForTerm:searchText];
  163. //有文字输入就把关键字传给handleSearchForTerm处理
  164. }
  165. -(void)searchBarCancelButtonClicked:(UISearchBar*)searchBar
  166. {//取消按钮被按下时触发
  167. [selfresetSearch];
  168. //重置
  169. searchBar.text=@"";
  170. //输入框清空
  171. [_tablereloadData];
  172. [_searchresignFirstResponder];
  173. //重新载入数据,隐藏软键盘
  174. }
  175. @end

mutableDeepCopy深复制的方法在NSDictionary+MutableDeepCopy定义,参考iOS/Objective-C开发 字典NSDictionary的深复制(使用category)
分享到:
评论

相关推荐

    ios-SearchBar和tableView快速索引.zip

    searchBar 和 tableView快速索引的结合使用 如发现问题请发邮件至ranheran@sohu.com,我会尽快修正

    SearchBar和tableView 组合并且不遮住状态栏

    ios7 demo下载 searchbar与状态栏重叠已修复。 关键代码: -(void)viewDidLoad{ [super viewDidLoad]; // self.table.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];//去除多余行 //设置table...

    iOS search

    - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{ NSLog(@"搜索Begin"); return YES; } - (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{ NSLog(@"搜索End"); return YES; } - ...

    iOS 10 App Development Essentials

    iOS 10 App Development Essentials: Learn to Develop iOS 10 Apps with Xcode 8 and Swift 3 Author: Neil Smyth Length: 816 pages Edition: 1 Language: English Publisher: CreateSpace Independent Publishing...

    史上最全的ios开发源码

    列表(Table)之TableView with SearchBar 列表(Table)之UITable嵌套UITable 列表(Table)之UploadProgressView 列表-Rainbow Styled Pull To Refresh 列表-UITableView背景随动 列表类》》自定义Table View折叠...

    searchBar与searchDisPlayController

    官方的searchBar与searchDisPlayController的用法,还有tableView

    iOS.8.App.Development.Essentials

    The key new features of the iOS 8 SDK and Xcode 6 are also covered, including Swift playgrounds, universal user interface design using size classes, app extensions, Interface Builder Live Views, ...

    ios-searchBar 搜索.zip

    可以修改颜色,字体,自定义,等等功能,需要让tableView更加丰富就需要自己写cell了,我是加在window上的,动画就一个简单的动画,向下兼容的可以考虑使用一些,注释就没怎么写了,都是比较基础的代码,一眼就懂了...

    iOS.9.App.Development.Essentials

    iOS 9 App Development Essentials is latest edition of this popular book series and has now been fully updated for the iOS 9 SDK, Xcode 7 and the Swift 2 programming language. Beginning with the ...

    iPhone development tableView sample

    本程序包括两个范例。 1。tableView的基本用法。 2。Navigation Table View的用法,包括searchBar的用法 全部源代码都是本人在Mac上测试通过。

    如何实现IOS_SearchBar搜索栏及关键字高亮

    这个就是所谓的搜索框了,那么接下来我们看看如何使用代码来实现这个功能. 我所使用的数据是英雄联盟的英雄名单,是一个JSON数据的txt文件, JSON数据的处理代码如下所示: //获取文件的路径path NSString *path = [...

    SwipeGesture和SearchBar

    此项目模仿高德地图搜索控件,主要解决了两个部分: 一是手势与tableView的scroll滑动冲突的问题; 还有一个就是searchBar的键盘以及searchBar在Editing状态下的动画问题。

    iOS-Contacts:模仿ios通讯录应用,实现基本通讯录功能

    iOS-Contacts模仿ios通讯录应用,实现...通讯录实现的细节:静态plist文件解析tableview根据分组列表显示删除联系人添加联系人分组内移动联系人顶部搜索框实现(UISearchController基本使用)导航栏以及searchbar设置

    SearchBarExample:一个带有 swift 的搜索栏示例

    概要说明这里是关于IOS中使用SearchBar的例子。使用到的技术点原生CoreDataplist文件的读取NSFetchedResultController结合TableView的使用TableView中右边添加了IndexSectionSearchBar的实现设置了tableView的...

    iphone单词程序

    初学iphone编程,一个英词单词小程序,代码中演示了tableView、searchBar、sqlite3的用法,非常简单,欢迎下载,相互学习!!

    模仿高德地图搜索控件 iOS

    作者AmoAmoAmo,源码SwipeGesture,模仿高德地图搜索控件。项目里有需要用到这个功能,看起来很简单很清晰的功能,可是真正当自己写的时候,...还有一个就是searchBar的键盘以及searchBar在Editing状态下的动画问题。

    iOS 实现模糊搜索的功能

    模糊搜索的实现思路是当搜索框开始编辑时对搜索框中的文本与后台给的资源相对比,包含搜索文本的展示在tableview中. 关键部分代码如下: -(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)...

    iphone通讯录

    storyboard,支持排序,字母检索,添加了搜索框,采用coredata数据库,支持添加删除修改联系人

    网狐V5源码下载 (开发库+系统模块)

    ├─开发库 │ ├─Include │ │ │ AndroidUserItem.h │ │ │ AndroidUserManager.h │ │ │ Array.h │ │ │ AvatarControlHead.h │ │ │ BitImage.h │ │ │ BitImageEx.h │ │ │ CameraControl.h │ ...

    ABExpandableView:可扩展,可折叠,可过滤和单多重选择的表格视图

    您应该具有2种模型对象才能使用此视图,其中一种应为section,另一种应为row。 考虑一下,Section和Row类是您的对象。 class Section : SectionItem { var identifier: String ! var name: String ! var

Global site tag (gtag.js) - Google Analytics