獲取iOS設備鍵盤高度


  最近做了一個自定義鍵盤,首先是要知道iOS設備各種鍵盤的高度,下面就來說一下怎么獲取鍵盤的高度。

  主要是利用鍵盤彈出時的通知。

  1、首先先隨便建一個工程。

  2、在工程的 -(void)viewDidload;函數中添加鍵盤彈出和隱藏的通知,具體代碼如下:

 1       //增加監聽,當鍵盤出現或改變時收出消息
 2       [[NSNotificationCenter defaultCenter] addObserver:self
 3                                             selector:@selector(keyboardWillShow:)
 4                                             name:UIKeyboardWillShowNotification
 5                                             object:nil];
 6 
 7       //增加監聽,當鍵退出時收出消息
 8       [[NSNotificationCenter defaultCenter] addObserver:self
 9                                             selector:@selector(keyboardWillHide:)
10                                             name:UIKeyboardWillHideNotification
11                                             object:nil];

  3、當得到通知時寫2個函數,來響應通知 -(void)keyboardWillShow; -(void)keyboardWillHide;

    在這2個函數中可以得到鍵盤的一些屬性,具體代碼如下:

 1 - (void)keyboardWillShow:(NSNotification *)aNotification
 2 {
 3     //獲取鍵盤的高度
 4     /*
 5      iphone 6:
 6      中文
 7      2014-12-31 11:16:23.643 Demo[686:41289] 鍵盤高度是  258
 8      2014-12-31 11:16:23.644 Demo[686:41289] 鍵盤寬度是  375
 9      英文
10      2014-12-31 11:55:21.417 Demo[1102:58972] 鍵盤高度是  216
11      2014-12-31 11:55:21.417 Demo[1102:58972] 鍵盤寬度是  375
12      
13      iphone  6 plus:
14      英文:
15      2014-12-31 11:31:14.669 Demo[928:50593] 鍵盤高度是  226
16      2014-12-31 11:31:14.669 Demo[928:50593] 鍵盤寬度是  414
17      中文:
18      2015-01-07 09:22:49.438 Demo[622:14908] 鍵盤高度是  271
19      2015-01-07 09:22:49.439 Demo[622:14908] 鍵盤寬度是  414
20      
21      iphone 5 :
22      2014-12-31 11:19:36.452 Demo[755:43233] 鍵盤高度是  216
23      2014-12-31 11:19:36.452 Demo[755:43233] 鍵盤寬度是  320
24      
25      ipad Air:
26      2014-12-31 11:28:32.178 Demo[851:48085] 鍵盤高度是  264
27      2014-12-31 11:28:32.178 Demo[851:48085] 鍵盤寬度是  768
28      
29      ipad2 :
30      2014-12-31 11:33:57.258 Demo[1014:53043] 鍵盤高度是  264
31      2014-12-31 11:33:57.258 Demo[1014:53043] 鍵盤寬度是  768
32      */
33     NSDictionary *userInfo = [aNotification userInfo];
34     NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
35     CGRect keyboardRect = [aValue CGRectValue];
36     int height = keyboardRect.size.height;
37     int width = keyboardRect.size.width;
38     NSLog(@"鍵盤高度是  %d",height);
39     NSLog(@"鍵盤寬度是  %d",width);
40 }
41 
42 //當鍵退出時調用
43 - (void)keyboardWillHide:(NSNotification *)aNotification
44 {
45 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM