当前位置: 代码迷 >> Iphone >> IPhone 之 UITableView 带搜寻
  详细解决方案

IPhone 之 UITableView 带搜寻

热度:657   发布时间:2016-04-25 06:37:03.0
IPhone 之 UITableView 带搜索

@interface TableViewAppDelegate : NSObject <UIApplicationDelegate> {        UIWindow *window;    UINavigationController *navigationController;}@property (nonatomic, retain) IBOutlet UIWindow *window;@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;@end #import "TableViewAppDelegate.h"#import "RootViewController.h"@implementation TableViewAppDelegate@synthesize window;@synthesize navigationController;#pragma mark -#pragma mark Application lifecycle- (void)applicationDidFinishLaunching:(UIApplication *)application {            // Override point for customization after app launch     [window addSubview:[navigationController view]];    [window makeKeyAndVisible];}- (void)applicationWillTerminate:(UIApplication *)application {// Save data if appropriate}#pragma mark -#pragma mark Memory management- (void)dealloc {[navigationController release];[window release];[super dealloc];}@end@interface RootViewController : UITableViewController <UISearchBarDelegate>{     NSDictionary *movieTitles;     NSArray *years;         //---search---     IBOutlet UISearchBar *searchBar;     BOOL isSearchOn;     BOOL canSelectRow;        NSMutableArray *listOfMovies;     NSMutableArray *searchResult; } @property (nonatomic, retain) NSDictionary *movieTitles; @property (nonatomic, retain) NSArray *years; //---search--- @property (nonatomic, retain) UISearchBar *searchBar; - (void) doneSearching: (id)sender; - (void) searchMoviesTableView; @end  #import "RootViewController.h"@implementation RootViewController@synthesize movieTitles, years; @synthesize searchBar; - (void)viewDidLoad {     NSString *path = [[NSBundle mainBundle] pathForResource:@"Movies" ofType:@"plist"];     NSDictionary *dic = [[NSDictionary alloc] initWithContentsOfFile:path];     self.movieTitles = dic;         NSArray *array = [[movieTitles allKeys]   sortedArrayUsingSelector:@selector(compare:)];     self.years = array;        [dic release];     //---display the searchbar---     self.tableView.tableHeaderView = searchBar;     searchBar.autocorrectionType = UITextAutocorrectionTypeYes;     //---copy all the movie titles in the dictionary into the listOfMovies array---     listOfMovies = [[NSMutableArray alloc] init];      for (NSString *year in array)    //---get all the years---     {         //---get all the movies for a particular year---         NSArray *movies = [movieTitles objectForKey:year];           for (NSString *title in movies)           {             [listOfMovies addObject:title];         }     }     //---used for storing the search result---     searchResult = [[NSMutableArray alloc] init];         isSearchOn = NO;     canSelectRow = YES;     [super viewDidLoad]; } //---? red when the user taps on the searchbar---   光标聚焦- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {     isSearchOn = YES;     canSelectRow = NO;     self.tableView.scrollEnabled = NO;     //---add the Done button at the top---     self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]                   initWithBarButtonSystemItem:UIBarButtonSystemItemDone   target:self action:@selector(doneSearching:)] autorelease]; } //---done with the searching---  点击done按钮- (void) doneSearching:(id)sender {     isSearchOn = NO;     canSelectRow = YES;     self.tableView.scrollEnabled = YES;     self.navigationItem.rightBarButtonItem = nil;     //---hides the keyboard---     [searchBar resignFirstResponder];     //---refresh the TableView---     [self.tableView reloadData]; } //---? red when the user types something into the searchbar---  有值输入- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {     //---if there is something to search for---  改变cell值 和 去掉tableView section(通过预先设定好的标志)      if ([searchText length] > 0) {         isSearchOn = YES;         canSelectRow = YES;         self.tableView.scrollEnabled = YES;         [self searchMoviesTableView];     }     else {                //---nothing to search---         isSearchOn = NO;         canSelectRow = NO;         self.tableView.scrollEnabled = NO;     }        [self.tableView reloadData]; } - (void) searchMoviesTableView {     //---clears the search result---     [searchResult removeAllObjects];     //过滤搜索结果    for (NSString *str in listOfMovies)     { //指定开始 匹配的location 和最大匹配长度//NSRange r;// r.location = 0;// r.length = 2;        NSRange titleResultsRange = [str rangeOfString:searchBar.text   options:NSCaseInsensitiveSearch range:r];NSLog(@"%@  %d   %d",str,titleResultsRange.length,titleResultsRange.location);        if (titleResultsRange.length > 0)             [searchResult addObject:str];     } NSLog(@"%d",[searchResult count]);} ///---? red when the user taps the Search button on the keyboard--- - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { [self searchMoviesTableView]; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {     if (isSearchOn)        return 1;     else         return [years count];    } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView  numberOfRowsInSection:(NSInteger)section {     if (isSearchOn) {         return [searchResult count];     } else     {         NSString *year = [years objectAtIndex:section];         NSArray *movieSection = [movieTitles objectForKey:year];        return [movieSection count];   } } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {         static NSString *CellIdentifier = @"Cell";         UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];     if (cell == nil) {         cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault   reuseIdentifier:CellIdentifier] autorelease];     }         // Configure the cell.     if (isSearchOn) {                NSString *cellValue = [searchResult objectAtIndex:indexPath.row];         cell.textLabel.text = cellValue;            } else {         NSString *year = [years objectAtIndex:[indexPath section]];         NSArray *movieSection = [movieTitles objectForKey:year];         cell.textLabel.text = [movieSection objectAtIndex:[indexPath row]];     }     return cell; } // 分区标题- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {     NSString *year = [years objectAtIndex:section];     if (isSearchOn)         return nil;     else         return year; }// tableView 右侧索引- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {     if (isSearchOn)         return nil;     else         return years; } //---fired before a row is selected---  cell是否可选- (NSIndexPath *)tableView :(UITableView *)theTableView    willSelectRowAtIndexPath:(NSIndexPath *)indexPath {     if (canSelectRow)         return indexPath;     else         return nil; } - (void)didReceiveMemoryWarning {     // Releases the view if it doesn't have a superview.     [super didReceiveMemoryWarning];         // Release any cached data, images, etc that aren't in use. } - (void)viewDidUnload {     // Release anything that can be recreated in viewDidLoad or on demand.     // e.g. self.myOutlet = nil; } - (void)dealloc {     [years release];     [movieTitles release];     [searchBar release];     [super dealloc]; } @end
?
  相关解决方案