本文實例為大家分享了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
運行結果
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答