本文实例为大家分享了tableview实现搜索功能的具体代码,供大家参考,具体内容如下
一、先用xcode创建好工程
通过xib文件来初始化视图控制器
二、编写代码
1、先为NSDictionary创建一个分类 实现字典的深拷贝
.h文件
#import <Foundation/Foundation.h>@interface NSDictionary (MutableDeepCopy)- (NSMutableDictionary *)mutableDeepCopy;
@end
.m文件
#import "NSDictionary+MutableDeepCopy.h"@implementation NSDictionary (MutableDeepCopy)- (NSMutableDictionary *)mutableDeepCopy{
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:[self count]];
//这里的容量也只是个参考值,表示对大小的限制 大小是调用该方法的count NSArray *keys = [self allKeys];
//self就是个可变的字典 for(id key in keys) {
id dicValue = [self valueForKey:key];
//从 NSDictionary 取值的时候有两个方法objectForkey valueForKey id dicCopy = nil;
if([dicValue respondsToSelector:@selector(mutableDeepCopy)]) //如果对象没有响应mutabledeepcopy 就创建一个可变副本 dicValue 有没有实现这个方法 {
dicCopy = [dicValue mutableDeepCopy];
}
else if([dicValue respondsToSelector:@selector(mutableCopy)]) {
dicCopy = [dicValue mutableCopy];
}
if(dicCopy ==nil) {
dicCopy = [dicValue copy];
}
[mutableDictionary setValue:dicCopy forKey:key];
}
return mutableDictionary;
}
@end
2、编写主代码
.h文件
NoteScanViewController.h
#import <UIKit/UIKit.h>@interface NoteScanViewController : UIViewController <UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>@property (nonatomic,retain)NSMutableDictionary *words;
@property (nonatomic,retain)NSMutableArray *keys;
@property (weak, nonatomic) IBOutlet UITableView *table;
@property (weak, nonatomic) IBOutlet UISearchBar *search;
@property (nonatomic,retain)NSDictionary *allWords;
- (void)resetSearch;
- (void)handleSearchForTerm:(NSString *)searchTerm;
@end
.m文件
#import "NoteScanViewController.h"#import "NSDictionary+MutableDeepCopy.h"@interface NoteScanViewController ()@end@implementation NoteScanViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization }
return self;
}
- (void)viewDidLoad //只在第一次加载视图调用{
[super viewDidLoad];
/*加载plist文件*/ NSString *wordsPath = [[NSBundle mainBundle]pathForResource:@"NoteSection" ofType:@"plist"];
//得到属性列表的路径 NSDictionary *dictionary = [[NSDictionary alloc]initWithContentsOfFile:wordsPath];
self.allWords = dictionary;
[self resetSearch];
//加载并填充words可变字典和keys数组 _search.autocapitalizationType = UITextAutocapitalizationTypeNone;
//不自动大写 _search.autocorrectionType = UITextAutocorrectionTypeNo;
//不自动纠错}
//取消搜索或者改变搜索条件- (void)resetSearch{
self.words = [self.allWords mutableDeepCopy];
//得到所有字典的副本 得到一个字典 NSLog(@"所有字典 = %@",self.words);
NSMutableArray *keyArray = [[NSMutableArray alloc]init];
//创建一个可变数组 [keyArray addObjectsFromArray:[[self.allWords allKeys]sortedArrayUsingSelector:@selector(compare:)]];
//用指定的selector对array的元素进行排序 self.keys = keyArray;
//将所有key 存到一个数组里面 NSLog(@"所有key = %@",self.keys);
}
//实现搜索方法- (void)handleSearchForTerm:(NSString *)searchTerm{
NSMutableArray *sectionsRemove = [[NSMutableArray alloc]init];
//创建一个数组存放我们所找到的空分区 [self resetSearch];
for(NSString *key in self.keys)//遍历所有的key {
NSMutableArray *array = [_words valueForKey:key] ;
//得到当前键key的名称 数组 NSMutableArray *toRemove = [[NSMutableArray alloc]init];
//需要从words中删除的值 数组 for(NSString *word in array) //实现搜索 {
if([word rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound)//搜索时忽略大小写 把没有搜到的值 放到要删除的对象数组中去 [toRemove addObject:word];
//把没有搜到的内容放到 toRemove中去 }
if([array count] == [toRemove count])//校对要删除的名称数组长度和名称数组长度是否相等 [sectionsRemove addObject:key];
//相等 则整个分区组为空 [array removeObjectsInArray:toRemove];
//否则 删除数组中所有与数组toRemove包含相同的元素 }
[self.keys removeObjectsInArray:sectionsRemove];
// 删除整个key 也就是删除空分区,释放用来存储分区的数组,并重新加载table 这样就实现了搜索 [_table reloadData];
}
- (void)viewWillAppear:(BOOL)animated //当使用Push或者prenset方式调用{
}
//#pragma mark -- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return ([_keys count] >0)?[_keys count]:1;
//搜索时可能会删除所有分区 则要保证要有一个分区}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if([_keys count] == 0) {
return 0;
}
NSString *key = [_keys objectAtIndex:section];
//得到第几组的key NSArray *wordSection = [_words objectForKey:key];
//得到这个key里面所有的元素 return [wordSection count];
//返回元素的个数}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSUInteger section = [indexPath section];
//得到第几组 NSUInteger row = [indexPath row];
//得到第几行 NSString *key = [_keys objectAtIndex:section];
//得到第几组的key NSArray *wordSection = [_words objectForKey:key];
//得到这个key里面的所有元素 static NSString *NoteSectionIdentifier = @"NoteSectionIdentifier";
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:NoteSectionIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NoteSectionIdentifier];
}
cell.textLabel.text = [wordSection objectAtIndex:row];
return cell;
}
//为每个分区指定一个标题- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
if([_keys count] == 0) return @" ";
NSString *key = [_keys objectAtIndex:section];
return key;
}
//创建一个索引表- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
return _keys;
}
#pragma mark - - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[_search resignFirstResponder];
//点击任意 cell都会取消键盘 return indexPath;
}
#pragma mark-- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar //搜索button点击事件{
NSString *searchTerm = [searchBar text];
[self handleSearchForTerm:searchTerm];
//搜索内容 删除words里面的空分区和不匹配内容}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
//搜索内容随着输入及时地显示出来 if([searchText length] == 0) {
[self resetSearch];
[_table reloadData];
return;
}
else [self handleSearchForTerm:searchText];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar //点击取消按钮{
_search.text = @"";
//标题 为空 [self resetSearch];
//重新 加载分类数据 [_table reloadData];
[searchBar resignFirstResponder];
//退出键盘}
@end
运行结果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
- iOS tableView实现搜索功能
- iOS开发之UITableView与UISearchController实现搜索及上拉加载,下拉刷新实例代码