如何使用UISearchController为UITableView创建搜索选项

时间:2016-01-05 07:17:24

标签: ios objective-c uitableview uisearchcontroller

我正在构建一个具有UITableView的应用程序(在我的firstviewcontroller中)。我从web service.data成功获取数据并成功显示在tableview中。这是我的firstviewcontroller .h和.m文件。

.h文件

@property (weak, nonatomic) IBOutlet UITableView *mtableView;
@property (strong, nonatomic) UISearchController *searchController;
@property (strong, nonatomic) NSMutableArray *airportList;
@property (strong, nonatomic) NSMutableArray *searchResults;

.m文件

- (void)viewDidLoad {
    [super viewDidLoad];

    [self getAirports];

    self.searchResults = airportList;
    NSLog(@"%@", self.searchResults);
    UINavigationController *searchResultsController = [[self storyboard] instantiateViewControllerWithIdentifier:@"TableSearchResultsNavController"];

    self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
    self.searchController.searchResultsUpdater = self;
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    self.mtableView.tableHeaderView = self.searchController.searchBar;
    self.definesPresentationContext = YES;        
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getAirports
{
    airportList = nil;
    NSString *neededData = [NSString stringWithFormat:@""];
    NSString *apiKey = [NSString stringWithFormat:@"some api key"];
    NSString *fullUrl = [NSString stringWithFormat:@"someurl%@%@",apiKey,neededData];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:fullUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSArray *result = (NSArray *)responseObject;
        airportList = [NSMutableArray array];
        for (NSDictionary *all in result)
        {
            Details *d1 = [Details new];
            d1.airport = [all objectForKey:@"Airport"];
            [airportList addObject:d1];
            [self.mtableView reloadData];

        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [airportList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ci"];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ci"];
    }

    Details *newDetails = [airportList objectAtIndex:indexPath.row];

    cell.textLabel.text = newDetails.airport;

    return cell;
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSString *searchString = [self.searchController.searchBar text];
    NSString *scope = nil;
    NSInteger selectedScopeButtonIndex = [self.searchController.searchBar selectedScopeButtonIndex];
    if (selectedScopeButtonIndex > 0) {
        scope = [airportList objectAtIndex:(selectedScopeButtonIndex -1)];
    }
    [self updateFilteredContentForAirportName:searchString];

    if (self.searchController.searchResultsController) {
        UINavigationController *navController = (UINavigationController *)self.searchController.searchResultsController;

        SearchResultsTableViewController *vc = (SearchResultsTableViewController *)navController.topViewController;
        vc.searchResults= self.searchResults;
        [vc.tableView reloadData];
    }     
}

- (void)updateFilteredContentForAirportName:(NSString *)airportName
{
    if ((airportName == nil) || [airportName length] == 0) {
        if (airportName == nil) {
            self.searchResults = airportList;
        }else{
            NSMutableArray *searchResults = [[NSMutableArray alloc] init];
            for (Details *detail in airportList) {
                if ([detail.airport isEqualToString:airportName]) {
                    [searchResults addObject:detail];
                }
                self.searchResults = searchResults;
            }
            return;
        }

        [self.searchResults removeAllObjects];

        for (Details *detail in airportList) {
            if ((airportName == nil) ||[detail.airport isEqualToString:airportName] ) {
                NSUInteger searchOptions = NSCaseInsensitiveSearch | NSCaseInsensitivePredicateOption;
                NSRange productNameRange = NSMakeRange(0, detail.airport.length);
                NSRange foundRange  = [detail.airport rangeOfString:airportName options:searchOptions range:productNameRange];
                if (foundRange.length > 0) {
                    [self.searchResults addObject:detail];
                }
            }
        }
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    Details *newDetails = [airportList objectAtIndex:indexPath.row];
    NSString *selectedText = newDetails.airport;
    [[NSUserDefaults standardUserDefaults] setObject:selectedText forKey:@"st"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [self dismissViewControllerAnimated:YES completion:nil];
}

然后我使用另一个UITableViewController来显示搜索结果。当我点击searchcontrller时,它会转到此tableviewcontroller的视图,但不显示任何内容(仅限默认的tableview)。 这是我的第二个视图(tableviewcontrller).h和.m文件

.h文件

@property (strong, nonatomic) NSMutableArray *searchResults;

.m文件

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [self.searchResults count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sc" forIndexPath:indexPath];

    cell.textLabel.text = [leakarray objectAtIndex:indexPath.row];

    // Configure the cell...

    return cell;
}

我将不胜感激任何帮助。

1 个答案:

答案 0 :(得分:0)

我不知道你为什么使用leakarray

cell.textLabel.text = [leakarray objectAtIndex:indexPath.row];

我认为你应该从self.searchResults数组中获取文本。

cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];

可能永远不会调用cellForRowAtIndexPath,因此请确保您在显示的dataSource中正确设置delegateUITableView secondViewController搜索结果。

您还可以通过在以下方法中添加断点来验证这一点

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

通过在控制点到达断点时添加断点检查以下可能性:
[self.searchResults count]应大于0