我在我的类(class)中包含了以下内容:
@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
确实出现在它应该出现的位置,并且在搜索栏时显示键盘被点击,但我的委托(delegate)方法都没有被调用。怎么回事?
最佳答案
您有一个名为searchController
的属性。但随后您在 configureSearchController
方法中创建了一个同名的局部变量。所以最终你永远不会设置 searchController
属性。因此,您本地创建的搜索 Controller 超出范围,不再有引用,并被释放。
修复方法是稍微更新您的代码。
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;
关于ios - 为什么我的 UISearchController 委托(delegate)方法没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50203583/