为什么我的UISearchController委托方法没有被调用?

时间:2018-05-06 19:15:29

标签: ios objective-c uisearchbar uisearchcontroller uisearchbardelegate

我在课堂上收录了以下内容:

@interface DiscoverNew() <UISearchResultsUpdating, UISearchBarDelegate, UISearchControllerDelegate>

我在这里设置UISearchController

-(void)viewDidLoad {

       [self configureSearchController];

}  

-(void)configureSearchController{

        // Initialize and perform a minimum configuration to the search controller.
        UISearchController *searchController = self.searchController;
        searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
        searchController.searchResultsUpdater = self;
        searchController.dimsBackgroundDuringPresentation = NO;
        searchController.searchBar.placeholder = @"Search for friends...";
        searchController.delegate = self;
        searchController.searchBar.delegate = self;
        [searchController.searchBar sizeToFit];

        [searchController.searchBar setBarStyle:UIBarStyleBlack];
        [searchController.searchBar setSearchBarStyle:UISearchBarStyleMinimal];
        searchController.searchBar.tintColor = [GBColor accentGray];
        searchController.searchBar.backgroundColor = [GBColor darkGray];
        searchController.searchBar.barTintColor = [GBColor accentGray];
        searchController.searchBar.searchTextPositionAdjustment = UIOffsetMake(18.0f, 0.0f);

        // Place searchbar above TableView
        self.tableView.tableHeaderView = searchController.searchBar;

}

正如您所看到的,我已调用searchController.searchBar.delegate = self; searchController确实出现在应有的位置,并且在点击搜索栏时会显示键盘,但我的委托方法都没有被调用。发生了什么事?

1 个答案:

答案 0 :(得分:1)

您有一个名为searchController的媒体资源。但是,然后在configureSearchController方法中创建一个同名的局部变量。所以最后你永远不会设置searchController属性。因此,您本地创建的搜索控制器超出范围,没有更多引用,并被取消分配。

修复方法是稍微更新您的代码。

UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
searchController.searchResultsUpdater = self;
searchController.dimsBackgroundDuringPresentation = NO;
searchController.searchBar.placeholder = @"Search for friends...";
searchController.delegate = self;
searchController.searchBar.delegate = self;
[searchController.searchBar sizeToFit];

[searchController.searchBar setBarStyle:UIBarStyleBlack];
[searchController.searchBar setSearchBarStyle:UISearchBarStyleMinimal];
searchController.searchBar.tintColor = [GBColor accentGray];
searchController.searchBar.backgroundColor = [GBColor darkGray];
searchController.searchBar.barTintColor = [GBColor accentGray];
searchController.searchBar.searchTextPositionAdjustment = UIOffsetMake(18.0f, 0.0f);

self.searchController = searchController;