我已经在navigatiom栏中实现了一个带有搜索栏的UISearchController,我想在加载视图时使搜索栏处于活动状态。当我说有效时,我的意思是键盘出现,用户可以在不点击搜索栏的情况下输入他/她的搜索。
我使用以下代码初始化了UISearchController:
- (void)viewDidLoad
{
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
[self.searchController setSearchResultsUpdater:self];
[self.searchController setDimsBackgroundDuringPresentation:NO];
[self.searchController setHidesNavigationBarDuringPresentation:NO];
[self.navigationItem setTitleView:self.searchController.searchBar];
[self setDefinesPresentationContext:YES];
[self.searchController.searchBar setDelegate:self];
[self.searchController.searchBar setShowsCancelButton:YES];
[self.searchController.searchBar setPlaceholder:@"City or Airfield"];
[self.searchController.searchBar sizeToFit];
}
我尝试将我的搜索控制器设为有效,请致电[self.searchController.searchBar becomeFirstResponder]
并直接致电searchBarSearchButtonClicked
,但无效。
答案 0 :(得分:12)
尝试拨打
[self.searchController setActive:YES]
之前
[self.searchController.searchBar becomeFirstResponder]
如果上述方法不起作用,请尝试以下方法:
- (void)viewDidLoad {
[super viewDidLoad];
...
[self initializeSearchController];
....
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.searchController setActive:YES];
[self.searchController.searchBar becomeFirstResponder];
}
- (void)initializeSearchController {
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.delegate = self;
self.searchController.searchBar.delegate = self;
[self.searchController.searchBar sizeToFit];
[self.tableView setTableHeaderView:self.searchController.searchBar];
self.definesPresentationContext = YES;
}
答案 1 :(得分:6)
要激活搜索栏:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.searchController setActive:YES];
}
" becomeFistResponder"只有在加载UISearchController时才能调用键盘。
- (void)didPresentSearchController:(UISearchController *)searchController
{
[searchController.searchBar becomeFirstResponder];
}
答案 2 :(得分:1)
除了做其他用户建议的内容外,我还做了以下工作,并且有效:
searchController.definesPresentationContext = YES;