iOS數字鍵台自訂按鍵,ios數字鍵台按鍵

來源:互聯網
上載者:User

iOS數字鍵台自訂按鍵,ios數字鍵台按鍵
UIKeyboardTypeNumberPad 數字鍵台自訂按鍵

最近做一個搜尋使用者的功能,這裡使用了UISearchBar。由於搜尋的方式只有手機號碼,所以這裡的鍵盤要限制為數字輸入,可以這麼做:
self.searchBar.keyboardType = UIKeyboardTypeNumberPad;


如果使用的不是搜尋方塊而是textField輸入框,可以設定textField的鍵盤屬性來展示

self.textField.keyboardType = UIKeyboardTypeNumberPad;

監聽事件如下所示即可。
 

 

但是這裡有個問題,就是數字鍵台上面沒有“搜尋”按鈕,這樣子使用者在輸入完手機號碼後無法搜尋。所以這個時候我們需要自己添加一個自訂的搜尋按鈕,然後加到鍵盤上面。

解決思路

這裡要注意的一點,隨著iOS SDK的不斷髮展,keyboard的視圖名稱也不斷在更新變化,當你調試以下代碼無法得到期待的效果時,請重新遍曆一次窗檯,然後慢慢調試,找到真正需要的視圖名稱。

解決代碼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,所以我們採用了延遲的方法。

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];        }    }}

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.