Dynamically Changing Keyboard Type for a UISearchBar

I have an iPhone app that uses a UISearchBar and UISearchDisplayController . The search bar has three scope buttons. I would like the keyboard to be a numeric keypad when a particular scope button is selected, but be a default keyboard when any other scope button is selected.

I have implemented the UISearchBarDelegate selectedScopeButtonIndexDidChange:selectedScope method as follows:

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

I know that the method gets called, and the right case gets triggered when the button in question is selected. But the onscreen keyboard doesn't change unless I tap the Cancel button to hide the keyboard, then tap the search field again to bring up the keyboard again.

Is there a way to get the keyboard to change itself while it's onscreen, or to programmatically hide it and then reshow it?


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.)


即使这是一种破解,这对我来说很有效:

- (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];

}

[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

链接地址: http://www.djcxy.com/p/7696.html

上一篇: UIView带走第一响应者状态

下一篇: 动态更改UISearchBar的键盘类型