iOS tableview实现简单搜索功能

 更新时间:2017年11月30日 14:36:13   作者:xunxun523  
这篇文章主要为大家详细介绍了iOS tableview实现简单搜索功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了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

运行结果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Flutter 模型动态化赋值研究分析

    Flutter 模型动态化赋值研究分析

    这篇文章主要为大家介绍了Flutter 模型动态化赋值研究分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-03-03
  • iOS NSTimer循环引用的几种解决办法

    iOS NSTimer循环引用的几种解决办法

    本篇文章主要介绍了iOS NSTimer循环引用的几种解决办法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-04-04
  • IOS中的target action控件的实现

    IOS中的target action控件的实现

    这篇文章主要介绍了IOS中的target action控件的实现的相关资料,这里提供实现target action的简单实例帮助大家学习理解该如何实现,需要的朋友可以参考下
    2017-08-08
  • IOS 关键字const 、static、extern详解

    IOS 关键字const 、static、extern详解

    这篇文章主要介绍了IOS 关键字const 、static、extern详解的相关资料,这里对关键字如何使用,及在IOS开发中的意义做了详解,需要的朋友可以参考下
    2016-11-11
  • Objective-C实现冒泡排序算法的简单示例

    Objective-C实现冒泡排序算法的简单示例

    冒泡排序即是依次比较相邻的两个数,如果后面的数较小则交换到前面一个数的位置上,这里我们来看一下Objective-C实现冒泡排序算法的简单示例
    2016-06-06
  • iOS11和iPhoneX适配的一些坑

    iOS11和iPhoneX适配的一些坑

    前阵子项目开发忙成狗,就一直没做iOS11的适配,直到XcodeGM版发布后,我胸有成竹的在iPhoneX上跑起项目,整个人都凉透了...下面总结一下我遇到的坑,感兴趣的朋友一起看看吧
    2017-09-09
  • iOS应用开发中监听键盘事件的代码实例小结

    iOS应用开发中监听键盘事件的代码实例小结

    这篇文章主要介绍了iOS应用开发中监听键盘事件的代码实例小结,呼出键盘等操作为iOS App中的必备功能,示例代码为传统的Objective-C,需要的朋友可以参考下
    2016-03-03
  • iOS之加载Gif图片的方法

    iOS之加载Gif图片的方法

    本篇文章主要介绍了iOS之加载Gif图片,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-11-11
  • 删除xcode 中过期的描述性文件方法

    删除xcode 中过期的描述性文件方法

    下面小编就为大家分享一篇删除xcode 中过期的描述性文件方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-01-01
  • iOS禁止所有输入法表情的方法

    iOS禁止所有输入法表情的方法

    这篇文章主要为大家详细介绍了iOS禁止所有输入法表情的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-10-10

最新评论