您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

如何取得 iOS 設備的鍵盤高度:透過鍵盤通知監聽

編輯:iOS 技巧大全
[摘要]本文介紹如何透過監聽鍵盤彈出與隱藏的通知,取得 iOS 設備上鍵盤的高度與寬度,並附上不同機型與語言下的實測數據供參考。

最近在製作一個自定義鍵盤,首先必須知道 iOS 各種設備、各種鍵盤的高度,下面就來說明如何取得鍵盤高度。

核心思路是利用鍵盤彈出時所發送的通知。

1、先隨便建立一個專案。

2、在專案的 - (void)viewDidLoad 方法中,加入鍵盤彈出與隱藏的通知監聽:

// 監聽鍵盤出現或改變時的通知
[[NSNotificationCenter defaultCenter] addObserver:self
                                        selector:@selector(keyboardWillShow:)
                                            name:UIKeyboardWillShowNotification
                                          object:nil];

// 監聽鍵盤退出時的通知
[[NSNotificationCenter defaultCenter] addObserver:self
                                        selector:@selector(keyboardWillHide:)
                                            name:UIKeyboardWillHideNotification
                                          object:nil];

3、收到通知後,撰寫兩個方法來響應:

- (void)keyboardWillShow:(NSNotification *)aNotification;
- (void)keyboardWillHide:(NSNotification *)aNotification;

在這些方法中就能取得鍵盤的相關屬性,程式碼如下:

- (void)keyboardWillShow:(NSNotification *)aNotification {
    // 取得鍵盤高度
    /* 實測數據參考:
       iPhone 6:中文 258 / 英文 216(寬度 375)
       iPhone 6 Plus:英文 226 / 中文 271(寬度 414)
       iPhone 5:216(寬度 320)
       iPad Air:264(寬度 768)
       iPad 2:264(寬度 768) */

    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    int width = keyboardRect.size.width;
    NSLog(@"鍵盤高度是 %d", height);
    NSLog(@"鍵盤寬度是 %d", width);
}

// 當鍵盤退出時呼叫
- (void)keyboardWillHide:(NSNotification *)aNotification {
}

關鍵在於從通知的 userInfo 中取出 UIKeyboardFrameEndUserInfoKey,即可獲得鍵盤的最終 frame,進而取得高度與寬度。由於不同機型、不同輸入法(中文或英文)下的鍵盤高度略有差異,因此建議以程式動態取得,而非寫死數值。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved