【发布时间】:2014-01-15 21:15:28
【问题描述】:
我正在尝试在 Xcode 中创建一个搜索栏,因此当您搜索一个项目时,您可以单击搜索结果单元格,它将转到视图控制器,但现在它所做的只是转到海景控制器并仅显示我单击的单元格的标签。
这是我的 .m 文件
@interface ListTableViewController () <UISearchDisplayDelegate>
@property (strong, nonatomic) NSArray *dataArray;
@property (strong, nonatomic) NSArray *searchResults;
@end
@implementation ListTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.dataArray = [NSArray arrayWithObjects:@"Tomb Raider", @"Little Big Planet", @"Unchanted 3", @"BlackOps 2", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)filterContentForSearchText: (NSString *) searchText
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", searchText];
self.searchResults = [self.dataArray filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString];
return YES;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
if (tableView == self.tableView) {
return [self.dataArray count];
} else { // (tableView == self.searchDisplayController.searchResultsTableView)
return [self.searchResults count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (tableView == self.tableView) {
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];
}
return cell;
}
#pragma mark - Table view delegate
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"showDetails"]) {
DetailsViewController *dvc = segue.destinationViewController;
NSIndexPath *indexPath = nil;
if ([self.searchDisplayController isActive]) {
indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
dvc.sendLabel = [self.searchResults objectAtIndex:indexPath.row];
return;
} else{
indexPath = [self.tableView indexPathForSelectedRow];
dvc.sendLabel = [self.dataArray objectAtIndex:indexPath.row];
return;
}
}
}
@end
谢谢,一切都会有帮助的。
【问题讨论】:
-
我不想代替你写所有控制器代码,但我认为如果你阅读本教程appcoda.com/how-to-add-search-bar-uitableview你应该找到答案。
-
我已经尝试过那个教程,它也有同样的问题。
-
你不能推送新的视图控制器,还是什么?说真的,我不明白你。请说明您的问题
-
当用户搜索一个词时,我希望他们点击该词并将他们定向到一个视图控制器,该控制器将为每个搜索词显示不同的信息。此外,不仅仅是一个标签。
标签: xcode search view controller