iOS鍵盤監聽以及獲取鍵盤高度

  在文本輸入時,界面會彈出鍵盤。有時,當文本輸入框太低,被鍵盤遮擋,使用戶沒法看見輸入框文本內容,這就使得用戶體驗太低。ide

  因此須要咱們對鍵盤進行監控並獲取鍵盤高度,調節界面或文本框高度進行處理。以下圖,文本輸入框太低的狀況:atom

     

  像這樣的狀況,如若未做處理,輸入框就會被鍵盤遮擋。這時,咱們須要監聽鍵盤事件,獲取鍵盤高度,對文本框視圖進行高度調整:spa

 1 #import "ViewController.h"
 2 
 3 @interface ViewController ()<UITextFieldDelegate>
 4 @property (weak, nonatomic) IBOutlet UITextField *inputField;
 5 // 拖線獲取的視圖約束對象
 6 @property (weak, nonatomic) IBOutlet NSLayoutConstraint *toBottom;
 7 
 8 @end
 9 
10 @implementation ViewController
11 
12 - (void)viewDidLoad {
13     [super viewDidLoad];
14     
15     self.inputField.delegate = self;
16  
17     // 添加通知監聽見鍵盤彈出/退出
18     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillShowNotification object:nil];
19     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillHideNotification object:nil];
20 }
21 
22 // 點擊非TextField區域取消第一響應者
23 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
24     [self.inputField resignFirstResponder];
25 }
26 
27 // 點擊鍵盤Return鍵取消第一響應者
28 - (BOOL)textFieldShouldReturn:(UITextField *)textField{
29     [self.inputField resignFirstResponder];
30     return  YES;
31 }
32 
33 // 點擊按鈕取,消第一響應者
34 - (IBAction)okAction:(UIButton *)sender {
35     [self.inputField resignFirstResponder];
36 }
37 
38 // 鍵盤監聽事件
39 - (void)keyboardAction:(NSNotification*)sender{
40     // 經過通知對象獲取鍵盤frame: [value CGRectValue]
41     NSDictionary *useInfo = [sender userInfo];
42     NSValue *value = [useInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
43     
44     // <注意>具備約束的控件經過改變約束值進行frame的改變處理
45     if([sender.name isEqualToString:UIKeyboardWillShowNotification]){
46         self.toBottom.constant = [value CGRectValue].size.height;
47     }else{
48         self.toBottom.constant = 0;
49     }
50 }
51 
52 - (void)didReceiveMemoryWarning {
53     [super didReceiveMemoryWarning];
54 }
55 
56 @end

  像這樣處理事後,輸入框視圖的位置就能夠隨鍵盤的彈出/退出而作相應的調整了:code

  

相關文章
相關標籤/搜索