Dynamically Changing Keyboard Type for a UISearchBar

后端 未结 3 1136
轻奢々
轻奢々 2020-12-14 20:32

I have an iPhone app that uses a UISearchBar and UISearchDisplayController. The search bar has three scope buttons. I would like the keyboard to

相关标签:
3条回答
  • 2020-12-14 20:33

    If you're using iOS 3.2 or newer, you can call:

    [searchBar reloadInputViews]
    

    and it switches immediately without hackery. At least this works for me on a UITextField. (I mention this because the resign/become first responder trick didn't work exactly right for me, but reloadInputViews did.)

    0 讨论(0)
  • 2020-12-14 20:35
    [searchBar reloadInputViews] 
    

    and

    [searchBar resignFirstResponder];
    [searchBar becomeFirstResponder];
    

    both can work, but the second method have more side effect, change firstResponder, can trigger keyboard's notification, so may affect other logic which depends on the keyboard's notification, and affect the view's frame which depend on keyboard frame's change

    0 讨论(0)
  • 2020-12-14 20:40

    Even though this is kind of a hack, this worked for me:

    - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope {
    
    
        switch (selectedScope) {
        case 0:
           searchBar.keyboardType = UIKeyboardTypeNumberPad;
            break;
       default:
            searchBar.keyboardType = UIKeyboardTypeDefault;
            break;
    
    
        // Hack: force ui to reflect changed keyboard type
        [searchBar resignFirstResponder];
        [searchBar becomeFirstResponder];
    
    }
    
    0 讨论(0)
提交回复
热议问题