【发布时间】:2014-05-14 22:17:19
【问题描述】:
我遇到了尝试在我的 UISearchDisplayController 和表视图控制器中显示搜索结果的问题。
我有用于获取搜索结果的 REST API 服务器端点,当用户单击搜索按钮并尝试将项目数组填充到搜索显示控制器中时,我正在发送请求。不幸的是,控制器的行为非常奇怪。
这是我的表格视图控制器的代码,在 viewDidLoad 方法中我正在初始化搜索:
LSDropdownViewController *menuCtrl = (LSDropdownViewController *)[self parentViewController];
[self setSearchBar:menuCtrl.topSearchBar];
[self.searchBar setDelegate:self];
[self.searchBar setBackgroundColor:[UIColor clearColor]];
[self.searchBar setBackgroundImage:[UIImage imageWithGradientColors]];
// set search cancel button color
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTintColor:[UIColor whiteColor]];
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:menuCtrl.topSearchBar contentsController:self];
[self.searchController setDelegate:self];
[self.searchController setSearchResultsDataSource:self.tableView.dataSource];
[self.searchController setSearchResultsDelegate:self.tableView.delegate];
我确实要求点击如下:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
MyHTTPClient *api = [MyHTTPClient create];
[api searchPopularCollectionsByText:searchBar.text success:^(AFHTTPRequestOperation *operation, id collections) {
[self.searchResults removeAllObjects];
NSArray *data = [collections objectForKey:@"data"];
if ([data count] > 0) {
NSMutableArray *result = [[NSMutableArray alloc] init];
for (NSDictionary *collectionData in data) {
LSCollection *collection = [[LSCollection alloc] initWithDictionary:collectionData];
[result addObject:collection];
}
[self.searchResults addObjectsFromArray:result];
[self.searchController.searchResultsTableView reloadData];
[result removeAllObjects];
result = nil;
}
} failure:nil];
}
如果响应包含项目数组,我将其填充到 searchResults 数组中,并在其他方法中检查正确的数据数组(例如在 cellForRowAtIndexPath 中):
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"collectionCell" forIndexPath:indexPath];
LSCollection *collection;
if (tableView == self.searchController.searchResultsTableView) {
collection = [self.searchResults objectAtIndex:indexPath.row];
} else {
collection = [self.collections objectAtIndex:indexPath.row];
}
...
但是看一下屏幕录像,有时searchResults 没有填充..
视频 http://screencast.com/t/enImJQuA
带有搜索结果位置的更多表格视图不固定,您也可以向下滚动到原始列表。
这里可能有什么错误?使用 REST 服务器处理点击搜索的正确方法是什么?
谢谢!
【问题讨论】:
-
您的
numberOfSections和numberOfRowsForSection方法是否正确处理为两个表视图提供正确的值? -
@rmaddy 我想是的,在这两种方法中,我都会检查哪个表视图当前处于活动状态 -
if (tableView == self.searchController.searchResultsTableView) -
我想实现同样的事情,请你帮帮我。
标签: ios objective-c arrays uisearchbar uisearchdisplaycontroller