Cannot set searchBar as firstResponder

前端 未结 21 1887
别跟我提以往
别跟我提以往 2020-11-30 01:33

I have a searchBar I\'m setting in a tableviewcontroller. i\'ve referenced this similar question UISearchBar cannot become first responder after UITableView did re-appear bu

21条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 02:28

    The solution with - (void)didPresentSearchController:(UISearchController *)searchController did not work, since this delegate method is called only when the user taps on the search bar...

    However, this solution did work:

    - (void) viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
        [self performSelector:@selector(showKeyboard) withObject:nil afterDelay:0.1];
    }
    
    - (void) showKeyboard
    {
        [self.searchController.searchBar becomeFirstResponder];
    }
    

    Swift 3

    delay(0.1) { self.searchController.searchBar.becomeFirstResponder() }
    
    func delay(_ delay: Double, closure: @escaping ()->()) {
        let when = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
    }
    

提交回复
热议问题