标签:
self.searchBar.keyboardType = UIKeyboardTypeNumberPad;
如果使用的不是搜索框而是textField输入框,可以设置textField的键盘属性来展示
self.textField.keyboardType = UIKeyboardTypeNumberPad;
监听事件如下所示即可。
但是这里有个问题,就是数字键盘上面没有“搜索”按钮,这样子用户在输入完手机号码后无法搜索。所以这个时候我们需要自己添加一个自定义的搜索按钮,然后加到键盘上面。
这里要注意的一点,随着iOS SDK的不断发展,keyboard的视图名称也不断在更新变化,当你调试以下代码无法得到期待的效果时,请重新遍历一次窗台,然后慢慢调试,找到真正需要的视图名称。
// 搜索按钮
_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,所以我们采用了延迟的方法。
- (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];
}
}
}
标签:
原文地址:http://www.cnblogs.com/MasterPeng/p/5802340.html