Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/100.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何使用UISearchController为UITableView设置搜索选项_Ios_Objective C_Uitableview_Uisearchcontroller - Fatal编程技术网

Ios 如何使用UISearchController为UITableView设置搜索选项

Ios 如何使用UISearchController为UITableView设置搜索选项,ios,objective-c,uitableview,uisearchcontroller,Ios,Objective C,Uitableview,Uisearchcontroller,我正在构建一个具有UITableView(在我的firstviewcontroller中)的应用程序。我从web服务获取数据。数据加载成功,并成功显示在tableview中。这是我的第一个ViewController.h和.m文件 .h文件 @property (weak, nonatomic) IBOutlet UITableView *mtableView; @property (strong, nonatomic) UISearchController *searchController;

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

.h文件

@property (weak, nonatomic) IBOutlet UITableView *mtableView;
@property (strong, nonatomic) UISearchController *searchController;
@property (strong, nonatomic) NSMutableArray *airportList;
@property (strong, nonatomic) NSMutableArray *searchResults;
@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];
}
#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;
}
然后我使用另一个
UITableViewController
来显示搜索结果。当我点击searchcontrller时,它进入这个tableviewcontroller的视图,但什么也不显示(只有默认的tableview)。 这是我的第二个视图(tableviewcontrller).h和.m文件

.h文件

@property (weak, nonatomic) IBOutlet UITableView *mtableView;
@property (strong, nonatomic) UISearchController *searchController;
@property (strong, nonatomic) NSMutableArray *airportList;
@property (strong, nonatomic) NSMutableArray *searchResults;
@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];
}
#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;
}

我将非常感谢您的帮助。

我不知道您为什么要使用leakarray

cell.textLabel.text = [leakarray objectAtIndex:indexPath.row];
我想你应该得到文本形式的self.searchResultsarray

cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];
可能是
cellforrowatinexpath
永远不会被调用,因此请确保在显示搜索结果的
secondViewController
中正确设置
dataSource
委派

您还可以通过在以下方法中放置断点来验证

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
通过在控件到达断点时添加断点检查以下可能性:

[self.searchResults count]
应该大于0

是否委托和数据源都是tableview?是的,对于第二个视图,我使用了tableviewController。因此,它已经随委托和数据源一起提供了。您是否在secondview中分配了NSMutableArray搜索结果?然后执行此操作?这就是为什么您没有获得搜索结果。我应该在何处执行此操作……我在帖子中编辑了此操作。我用那个数组来检查。我很抱歉。我检查了断点。在numberofRowsInSection方法中,count始终为0,因此现在需要检查
firstViewController的getAirports方法中的
self.searchResults
的值。