动态更改UISearchBar的键盘类型

15

我有一个使用 UISearchBarUISearchDisplayController 的iPhone应用程序。搜索栏有三个范围按钮。当选择特定的范围按钮时,我希望键盘是数字键盘,而其他任何范围按钮被选择时,则为默认键盘。

我已经实现了 UISearchBarDelegateselectedScopeButtonIndexDidChange:selectedScope 方法如下:

- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
{
    switch (selectedScope) {
        case DeviceIDScopeIndex:
            searchBar.keyboardType = UIKeyboardTypeNumberPad;
            break;
        default:
            searchBar.keyboardType = UIKeyboardTypeDefault;
            break;
    }
}
我知道当选择相关按钮时,方法会被调用并且正确的情况会触发。但是屏幕上的键盘除非我点击取消按钮来隐藏键盘,然后再次点击搜索框才能弹出键盘,不然它就不会改变。有没有办法在键盘显示时使其自己改变,或者编程方式隐藏然后重新显示键盘?
3个回答

29

如果你使用的是iOS 3.2或更新版本,你可以调用以下方法:

[searchBar reloadInputViews]

并且它可以立即切换,无需任何奇技淫巧。至少在UITextField上对我有效。(我提到这一点是因为resign/become first responder技巧在我身上并没有完全起作用,但reloadInputViews却能解决问题。)


1
请注意,在Xcode 4.2用于iOS 5.0.1的大多数情况下,“[searchBar reloadInputViews]”无法正常工作。所使用的键盘类型是在storyboard中指定的,我只能在“(void)searchBar:(UISearchBar *)aSearchBar textDidChange:(NSString *)searchText”内更改keyboardType。我已尝试在VDL中更改它,在UIKeyboardDidShowNotification后也试过,但都没有用。 - Alex Zavatone
我发现这个方法存在一个缺点:如果用户同时输入数字和字母,调用该方法将自动切换到字母键盘,即使他想继续输入数字。 - anavarroma
这应该是被接受的答案。辞职和设置第一响应者可能会产生意想不到的副作用。 - Hunter Monk
1
很遗憾(2019年),这对我不起作用 - 似乎你必须辞职/成为。是的,您必须在文本输入处理代码中小心处理。 - Fattie

23

虽然这有点像是一种hack方法,但是这对我起作用了:

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

}

1
谢谢。我想到这可能是解决方案,但希望有更简洁的方法。 - Kristopher Johnson
2
有趣的是,如果你立即在一起调用resignFirstResponder和becomeFirstResponder,键盘会切换而不会被解除。 - nduplessis

1
[searchBar reloadInputViews] 

[searchBar resignFirstResponder];
[searchBar becomeFirstResponder];

两种方法都可以工作,但第二种方法有更多的副作用,会改变firstResponder,可能触发键盘的通知,从而影响依赖于键盘通知的其他逻辑,并且会影响依赖于键盘框架变化的视图的框架。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接