Сейчас я разрабатываю приложение, которое состоит из табличного представления с панелью поиска. Когда кто-то нажимает на одну из строк таблицы, он загружает новое представление с соответствующей страницей. Это мой код:
RootViewController.h:
@interface RootViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate, UISearchBarDelegate>
{
UITableView *mainTableView;
NSMutableArray *contentsList;
NSMutableArray *searchResults;
NSString *savedSearchTerm;
}
@property (nonatomic, retain) IBOutlet UITableView *mainTableView;
@property (nonatomic, retain) NSMutableArray *contentsList;
@property (nonatomic, retain) NSMutableArray *searchResults;
@property (nonatomic, copy) NSString *savedSearchTerm;
- (void)handleSearchForTerm:(NSString *)searchTerm;
@end
RootViewController.m:
#import "RootViewController.h"
#import "Hydrogen.h"
#import "Helium.h"
@implementation RootViewController
@synthesize mainTableView;
@synthesize contentsList;
@synthesize searchResults;
@synthesize savedSearchTerm;
- (void)dealloc
{
[mainTableView release], mainTableView = nil;
[contentsList release], contentsList = nil;
[searchResults release], searchResults = nil;
[savedSearchTerm release], savedSearchTerm = nil;
[super dealloc];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Save the state of the search UI so that it can be restored if the view is re-created.
[self setSavedSearchTerm:[[[self searchDisplayController] searchBar] text]];
[self setSearchResults:nil];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:@"Hydrogen"];
[array addObject:@"Helium"];
[self setContentsList:array];
[array release], array = nil;
// Restore search term
if ([self savedSearchTerm])
{
[[[self searchDisplayController] searchBar] setText:[self savedSearchTerm]];
}
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[self mainTableView] reloadData];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (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)handleSearchForTerm:(NSString *)searchTerm
{
[self setSavedSearchTerm:searchTerm];
if ([self searchResults] == nil)
{
NSMutableArray *array = [[NSMutableArray alloc] init];
[self setSearchResults:array];
[array release], array = nil;
}
[[self searchResults] removeAllObjects];
if ([[self savedSearchTerm] length] != 0)
{
for (NSString *currentString in [self contentsList])
{
if ([currentString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound)
{
[[self searchResults] addObject:currentString];
}
}
}
}
#pragma mark -
#pragma mark UITableViewDataSource Methods
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
NSInteger rows;
if (tableView == [[self searchDisplayController] searchResultsTableView])
rows = [[self searchResults] count];
else
rows = [[self contentsList] count];
return rows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row = [indexPath row];
NSString *contentForThisRow = nil;
if (tableView == [[self searchDisplayController] searchResultsTableView])
contentForThisRow = [[self searchResults] objectAtIndex:row];
else
contentForThisRow = [[self contentsList] objectAtIndex:row];
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// Do anything that should be the same on EACH cell here. Fonts, colors, etc.
}
// Do anything that COULD be different on each cell here. Text, images, etc.
[[cell textLabel] setText:contentForThisRow];
return cell;
}
#pragma mark -
#pragma mark UITableViewDelegate Methods
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if ([[contentsList objectAtIndex:indexPath.row] isEqual:@"Hydrogen"])
{
Hydrogen *hydrogen = [[Hydrogen alloc] initWithNibName:@"Hydrogen" bundle:nil];
[self.navigationController pushViewController:hydrogen animated:YES];
[hydrogen release];
}
else if ([[contentsList objectAtIndex:indexPath.row] isEqual:@"Helium"])
{
Helium *helium = [[Helium alloc] initWithNibName:@"Helium" bundle:nil];
[self.navigationController pushViewController:helium animated:YES];
[helium release];
}
}
#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self handleSearchForTerm:searchString];
return YES;
}
- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
[self setSavedSearchTerm:nil];
[[self mainTableView] reloadData];
}
@end
Этот код работает отлично, за исключением одного недостатка. Когда я использую поиск, результаты отображаются, как и ожидалось, с результатами, совпадающими с введенной строкой. Однако, когда я нажимаю на одну из строк результатов поиска, соответствующий файл XIB не загружается; вместо этого он загружает файл XIB, который соответствует исходному тексту в UITableView без поиска.
Например, если бы я в поиске набрал слово «Гелий», он отобразил бы один результат «Гелий», но когда я нажал на результат, он загрузил страницу «Водород», потому что водород был исходная ссылка, к которой был получен доступ при первом касании.
Может кто-нибудь помочь мне с этим? Я потратил много дней на этот код, и он действительно расстраивает.
Спасибо всем, кто может мне очень-очень помочь!