iOS tableview 간단 한 검색 기능 구현
1.먼저 xcode 로 프로젝트 를 만 듭 니 다.
보기 컨트롤 러 를 xib 파일 로 초기 화 합 니 다.
코드 작성
1.먼저 NSDictionary 에 사전 의 깊 은 복사 분 류 를 만 듭 니 다.
.h 파일
#import <Foundation/Foundation.h>
@interface NSDictionary (MutableDeepCopy)
- (NSMutableDictionary *)mutableDeepCopy;
@end
파일
#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
파일
#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
실행 결과이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
View의 레이아웃 방법을 AutoLayout에서 따뜻한 손 계산으로 하면 성능이 9.26배로 된 이야기이 기사는 의 15 일째 기사입니다. 어제는 에서 이었습니다. 손 계산을 권하는 의도는 없고, 특수한 상황하에서 계측한 내용입니다 화면 높이의 10 배 정도의 contentView가있는 UIScrollView 레이아...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.