self.searchBar.keyboardType = UIKeyboardTypeNumberPad;
若是使用的不是搜索框而是textField输入框,能够设置textField的键盘属性来展现
self.textField.keyboardType = UIKeyboardTypeNumberPad;
监听事件以下所示便可。
可是这里有个问题,就是数字键盘上面没有“搜索”按钮,这样子用户在输入完手机号码后没法搜索。因此这个时候咱们须要本身添加一个自定义的搜索按钮,而后加到键盘上面。windows
这里要注意的一点,随着iOS SDK的不断发展,keyboard的视图名称也不断在更新变化,当你调试如下代码没法获得期待的效果时,请从新遍历一次窗台,而后慢慢调试,找到真正须要的视图名称。bash
// 搜索按钮
_searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
_searchButton.frame = CGRectMake(0, 163, 106, 53); [_searchButton setTitle:@"搜索" forState:UIControlStateNormal]; [_searchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [_searchButton addTarget:self action:@selector(SearchButtonDidTouch:) forControlEvents:UIControlEventTouchUpInside];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowOnDelay:) name:UIKeyboardWillShowNotification object:nil]; - (void)keyboardWillShowOnDelay:(NSNotification *)notification { [self performSelector:@selector(keyboardWillShow:) withObject:nil afterDelay:0]; }
这里面监听通知后的执行函数并不是立马执行查找窗体的函数,是由于在iOS4后,键盘添加到窗体的事件放到了下一个EventLoop,因此咱们采用了延迟的方法。ide
- (void)keyboardWillShow:(NSNotification *)notification { UIView *foundKeyboard = nil; UIWindow *keyboardWindow = nil; for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) { if (![[testWindow class] isEqual:[UIWindow class]]) { keyboardWindow = testWindow; break; } } if (!keyboardWindow) return; for (__strong UIView *possibleKeyboard in [keyboardWindow subviews]) { if ([[possibleKeyboard description] hasPrefix:@"<UIInputSetContainerView"]) { for (__strong UIView *possibleKeyboard_2 in possibleKeyboard.subviews) { if ([possibleKeyboard_2.description hasPrefix:@"<UIInputSetHostView"]) { foundKeyboard = possibleKeyboard_2; } } } } if (foundKeyboard) { if ([[foundKeyboard subviews] indexOfObject:_searchButton] == NSNotFound) { [foundKeyboard addSubview:_searchButton]; } else { [foundKeyboard bringSubviewToFront:_searchButton]; } } }