iOS開發(fā)之UIKeyboardTypeNumberPad數(shù)字鍵盤自定義按鍵
最近做一個搜索用戶的功能,這里使用了UISearchBar。由于搜索的方式只有手機號碼,所以這里的鍵盤要限制為數(shù)字輸入,可以這么做:
self.searchBar.keyboardType = UIKeyboardTypeNumberPad;如果使用的不是搜索框而是textField輸入框,可以設(shè)置textField的鍵盤屬性來展示 self.textField.keyboardType = UIKeyboardTypeNumberPad;監(jiān)聽事件如下所示即可。
但是這里有個問題,就是數(shù)字鍵盤上面沒有“搜索”按鈕,這樣子用戶在輸入完手機號碼后無法搜索。所以這個時候我們需要自己添加一個自定義的搜索按鈕,然后加到鍵盤上面。
解決思路如下所示:
1.自定義搜索button
2.監(jiān)聽鍵盤出現(xiàn)的事件
3.遍歷搜索的Windows窗體,找到鍵盤的窗體,然后遍歷其子視圖,找到我們真正需要的鍵盤視圖
4.把我們自定義的按鈕加到上面找到的視圖里
這里要注意的一點,隨著iOS SDK的不斷發(fā)展,keyboard的視圖名稱也不斷在更新變化,當(dāng)你調(diào)試以下代碼無法得到期待的效果時,請重新遍歷一次窗臺,然后慢慢調(diào)試,找到真正需要的視圖名稱。
解決代碼
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.監(jiān)聽鍵盤出現(xiàn)的事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowOnDelay:) name:UIKeyboardWillShowNotification object:nil]; - (void)keyboardWillShowOnDelay:(NSNotification *)notification { [self performSelector:@selector(keyboardWillShow:) withObject:nil afterDelay:0]; }
這里面監(jiān)聽通知后的執(zhí)行函數(shù)并非立馬執(zhí)行查找窗體的函數(shù),是因為在iOS4后,鍵盤添加到窗體的事件放到了下一個EventLoop,所以我們采用了延遲的方法。
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]; } } }
以上所述是小編給大家介紹的iOS開發(fā)之UIKeyboardTypeNumberPad數(shù)字鍵盤自定義按鍵,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
IOS 開發(fā)之swift中UIView的擴展使用的實例
這篇文章主要介紹了IOS 開發(fā)之swift中UIView的擴展使用的實例的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下2017-09-09iOS8調(diào)用相機報警告Snapshotting a view的解決方法
這篇文章主要介紹了iOS8調(diào)用相機報警告Snapshotting a view……的解決方法 ,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11IOS內(nèi)存泄漏檢查方法及重寫MLeakFinder
這篇文章主要介紹了IOS內(nèi)存泄漏檢查方法及如何重寫MLeakFinder,幫助ios開發(fā)者維護自身程序,感興趣的朋友可以了解下2021-04-04關(guān)于iOS導(dǎo)航欄返回按鈕問題的解決方法
這篇文章主要為大家詳細介紹了關(guān)于iOS導(dǎo)航欄返回按鈕問題的解決方法,對iOS自定義backBarButtonItem的點擊事件進行介紹,感興趣的小伙伴們可以參考一下2016-05-05