最近做了一個搜尋使用者的功能,畫面上用 UISearchBar。因為只支援以手機號碼搜尋,鍵盤必須限制為數字輸入,做法很簡單:
self.searchBar.keyboardType = UIKeyboardTypeNumberPad;
如果用的是 UITextField,也一樣設定它的鍵盤型別即可:
self.textField.keyboardType = UIKeyboardTypeNumberPad;

問題在這裡出現了:數字鍵盤上沒有「搜尋」鈕,使用者輸完號碼無處可按,只能先收起鍵盤再點搜尋框,操作上非常彆扭。因此我們需要自己補一顆自訂按鈕,並把它掛到鍵盤上。
解決思路
1. 建立自訂的搜尋按鈕。
2. 監聽鍵盤即將顯示的通知。
3. 遍歷 App 的所有 UIWindow,找到鍵盤所在的窗體,再往下找子視圖,直到真正的鍵盤容器視圖。
4. 把自訂按鈕加到找到的視圖上。
這裡有個重要前提:隨著 iOS SDK 演進,鍵盤的視圖層級與類別名稱一直會變。當你發現下面的程式碼跑不出預期效果時,請把整棵視圖樹印出來(遞迴印 subviews 與 className),逐層確認目前版本的鍵盤容器叫什麼名字。
解決程式碼
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];
}
這裡刻意不直接呼叫查找視圖的方法,而是延遲到下一個迴圈。原因是從 iOS 4 之後,鍵盤加入窗體的動作被放到下一個 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];
}
}
}

完成後如下圖,數字鍵盤上多了一顆自訂的搜尋鈕,操作流程順暢許多。
補充一點:這種做法屬於操作私有視圖層級,官方並不保證相容性,上架審核也有風險。若只是要「打完字按確認」,更穩妥的替代方案是改用 UIKeyboardTypeNumbersAndPunctuation 搭配自訂 inputView,或直接在鍵盤上方加一條 UIToolbar / inputAccessoryView 放完成鈕,這樣完全不依賴私有結構,也不會隨 iOS 版本升級而失效。
以上就是為數字鍵盤加上自訂按鍵的完整做法,希望對大家有幫助。有任何疑問歡迎留言。