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]; 
} 






//---fi 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]; 
} 


//---fi 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]);
} 

///---fi 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
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值