我已经在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,但没有任何作用.
解决方法
试着打电话
[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; }