ios – 使UISearchController搜索栏自动激活

前端之家收集整理的这篇文章主要介绍了ios – 使UISearchController搜索栏自动激活前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经在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;
}
原文链接:https://www.f2er.com/iOS/332675.html

猜你在找的iOS相关文章