IOS tableview realizes simple search function

Time:2021-1-16

This example for you to share the tableview search function of the specific code, for your reference, the specific content is as follows

1、 Create a project with Xcode first

Initialize view controller through Xib file

2、 Write the code

1. First, create a classification for nsdictionary to realize the deep copy of the dictionary

. h file


#import <Foundation/Foundation.h>

@interface NSDictionary (MutableDeepCopy)

- (NSMutableDictionary *)mutableDeepCopy;
@end


. m file

#import "NSDictionary+MutableDeepCopy.h"

@implementation NSDictionary (MutableDeepCopy)

- (NSMutableDictionary *)mutableDeepCopy
{
 Nsmutabledictionary * mutabledictionary = [nsmutabledictionary dictionarywithcapacity: [self count]; // the capacity here is only a reference value, indicating the size limit. The size is the count of calling the method
 Nsarray * keys = [self allkeys]; // self is a variable dictionary
 for(id key in keys)
 {
  id dicValue = [self valueForKey:key]; 
  //There are two methods for fetching values from nsdictionary: objectforkey valueforkey
  id dicCopy = nil;
  if([dicValue respondsToSelector:@selector(mutableDeepCopy)]) 
  //If the object does not respond to mutabledeep copy, a mutable copy is created. Does dicvalue implement this method
  {
   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. Write the main code

. h file
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 file

#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 // called only when the view is loaded for the first time
{
 [super viewDidLoad];
 /*Load plist file*/
 Nsstring * wordpath = [[nsbundle mainbundle] pathforresource: @ "notesection" of type: @ "plist]; // get the path of the attribute list
 NSDictionary *dictionary = [[NSDictionary alloc]initWithContentsOfFile:wordsPath];
 self.allWords = dictionary;
 [self resetsearch]; // load and fill in the words variable dictionary and keys array
 
 _ search.autocapitalizationType  =Uitextautocapitalizationtypenone; // no auto capitalization
 _ search.autocorrectionType  =Uitextautocorrectiontypeno; // no auto correction
}

//Cancel the search or change the search criteria
- (void)resetSearch
{
 self.words  = [ self.allWords  Mutabledeepcopy]; // get copies of all dictionaries to get one dictionary
 Nslog (@ "all dictionaries =% @", self.words );
 Nsmutablearray * keyarray = [[nsmutablearray alloc] init]; // create a variable array
 [keyArray addObjectsFromArray:[[ self.allWords  allKeys] sortedArrayUsingSelector:@selector (compare:)]; // use the specified selector to sort the elements of the array
 self.keys  =Keyarray; // store all keys in an array
 Nslog (@ "all keys =% @", self.keys );
}
//Implementation of search methods
- (void)handleSearchForTerm:(NSString *)searchTerm
{
 Nsmutablearray * sectionsremove = [[nsmutablearray alloc] init]; // create an array to store the empty partition we found
 [self resetSearch];
 for(NSString *key in  self.keys )//Traverse all the keys
 {
  NSMutableArray *array = [_ words va lueForKey:key ]; // get the name array of the current key
  Nsmutablearray * toremove = [[nsmutablearray alloc] init]; // value array to be deleted from words
  For (nsstring * word in array) // search
  {
   if([word rang eOfString:searchTerm options : nscaseinsensitivesearch]. Location = = nsnotfound) // ignore case when searching, and put the value not found into the object array to be deleted
    [toRemove  addObject:word ]; // put the contents not found in toremove
  }
  
  If ([array count] = [toremove count]) // check whether the length of the name array to be deleted is equal to that of the name array
   [sectionsRemove  addObject:key ]; // equal, the entire partition group is empty
  [array removeObjec tsInArray:toRemove ]; // otherwise, delete all elements in the array that contain the same elements as the array toremove
 }
 [ self.keys  removeObjec tsInArray:sectionsRemove ]; // to delete the whole key is to delete the empty partition, release the array used to store the partition, and reload the table, so as to realize the search
 [_table reloadData];
}

-(void) viewwillappearance: (bool) animated // when called by push or preset
{
}
//#pragma mark -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
 return ([_ keys count] >0)?[_ Keys count]: 1; // when searching, all partitions may be deleted, so make sure there is one partition
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
 if([_keys count] == 0)
 {
  return 0;
 }
 NSString *key = [_ keys obje ctAtIndex:section ]; // get the key of the group
 NSArray *wordSection = [_ words obj ectForKey:key ]; // get all the elements in the key
 Return [wordsection count]; // returns the number of elements
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 Nsuinteger section = [indexpath section]; // which group do you get
 Nsuinteger row = [indexpath row]; // get the line number
 NSString *key = [_ keys obje ctAtIndex:section ]; // get the key of the group
 NSArray *wordSection = [_ words obj ectForKey:key ]; // get all the elements in the 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;
}
//Specify a title for each partition
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
 if([_keys count] == 0)
  return @" ";
 NSString *key = [_keys objectAtIndex:section];
 return key;
}
//Create an index table
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
 return _keys;
}
#pragma mark - 

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 [_ Search resignfirstresponder]; // clicking any cell will cancel the keyboard
 return indexPath;
}

#pragma mark-

-(void) searchbarsearchbuttonclicked: (UISearchBar *) searchBar // search button click event
{
 NSString *searchTerm = [searchBar text];
 [self handleSear chForTerm:searchTerm ]; // search for content and delete empty partitions and unmatched content in words
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{// the search content is displayed in time with the input
 if([searchText length] == 0)
 {
  [self resetSearch];
  [_table reloadData];
  return;
 }
 else
  [self handleSearchForTerm:searchText];
}

-(void) searchbarcancelbuttonclicked: (UISearchBar *) searchBar // click the Cancel button
{
 _ search.text  [email protected] "; // the title is empty
 [self resetsearch]; // reload classification data
 [_table reloadData];
 [searchBar resignfirstresponder]; // exit the keyboard

}
@end

Running results

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.