iOS數字鍵盤自定義按鍵

UIKeyboardTypeNumberPad 數字鍵盤自定義按鍵


最近作一個搜索用戶的功能,這裏使用了UISearchBar。因爲搜索的方式只有手機號碼,因此這裏的鍵盤要限制爲數字輸入,能夠這麼作:

self.searchBar.keyboardType = UIKeyboardTypeNumberPad;


若是使用的不是搜索框而是textField輸入框,能夠設置textField的鍵盤屬性來展現

self.textField.keyboardType = UIKeyboardTypeNumberPad;

監聽事件以下所示便可。
 

 

這裏寫圖片描述

可是這裏有個問題,就是數字鍵盤上面沒有「搜索」按鈕,這樣子用戶在輸入完手機號碼後沒法搜索。因此這個時候咱們須要本身添加一個自定義的搜索按鈕,而後加到鍵盤上面。windows

解決思路

  1. 自定義搜索button
  2. 監聽鍵盤出現的事件
  3. 遍歷搜索的Windows窗體,找到鍵盤的窗體,而後遍歷其子視圖,找到咱們真正須要的鍵盤視圖
  4. 把咱們自定義的按鈕加到上面找到的視圖裏

這裏要注意的一點,隨着iOS SDK的不斷髮展,keyboard的視圖名稱也不斷在更新變化,當你調試如下代碼沒法獲得期待的效果時,請從新遍歷一次窗臺,而後慢慢調試,找到真正須要的視圖名稱。bash

解決代碼

1.自定義搜索按鈕
// 搜索按鈕
    _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]; 

 

2.監聽鍵盤出現的事件
[[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

3. 遍歷視圖,並添加按鈕
- (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]; } } }

 

這裏寫圖片描述

相關文章
相關標籤/搜索