代码之家  ›  专栏  ›  技术社区  ›  Kristopher Johnson

动态更改UISearchBar的键盘类型

  •  13
  • Kristopher Johnson  · 技术社区  · 15 年前

    我有一个iPhone应用程序,它使用 UISearchBar UISearchDisplayController . 搜索栏有三个范围按钮。我希望键盘在选择特定范围按钮时是数字键盘,但在选择任何其他范围按钮时是默认键盘。

    我已经实施了 UISearchBarDelegate selectedScopeButtonIndexDidChange:selectedScope 方法如下:

    - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
    {
        switch (selectedScope) {
            case DeviceIDScopeIndex:
                searchBar.keyboardType = UIKeyboardTypeNumberPad;
                break;
            default:
                searchBar.keyboardType = UIKeyboardTypeDefault;
                break;
        }
    }
    

    我知道该方法会被调用,并且当选择了有问题的按钮时会触发正确的案例。但屏幕上的键盘不会改变,除非我点击“取消”按钮隐藏键盘,然后再次点击“搜索”字段再次调出键盘。

    有没有办法让键盘在屏幕上时自行更改,或者通过编程将其隐藏,然后重新显示?

    3 回复  |  直到 15 年前
        1
  •  27
  •   Jeff Menter    13 年前

    如果您使用的是iOS 3.2或更高版本,您可以拨打:

    [searchBar reloadInputViews]
    

    而且它可以在没有黑客攻击的情况下立即切换。至少在UITextField上这对我有用。(我之所以提到这一点,是因为辞职/成为第一响应者的伎俩对我来说并不完全有效,但reloadInputViews确实有效。)

        2
  •  23
  •   zaheer    11 年前

    尽管这是一种黑客行为,但对我来说很有效:

    - (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];
    
    }
    
        3
  •  1
  •   Parag Bafna    8 年前
    [searchBar reloadInputViews] 
    

    [searchBar resignFirstResponder];
    [searchBar becomeFirstResponder];
    

    两者都可以工作,但第二种方法有更多的副作用,更改firstResponder,可以触发键盘通知,因此可能会影响依赖于键盘通知的其他逻辑,并影响依赖于键盘帧更改的视图帧