在一些網站登陸界面,我們經常會見到,鍵盤的出現與隱藏操作,那么基于代碼是如何實現的呢?下面小編寫了具體代碼介紹,特此分享到服務器之家平臺,供大家參考
具體代碼如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
# import "ViewController.h" # import "UIView+FrameExtension.h" // 可以自己寫,以后用著方便 #define kDeviceHeight [UIScreen mainScreen].bounds.size.height @interface ViewController () @end @implementation ViewController - ( void )viewDidLoad { [ super viewDidLoad]; // 設置視圖的背景色 self.view.backgroundColor = [UIColor lightGrayColor]; // 添加第一個文本框 假定位置 UITextField *firstField = [[UITextField alloc]initWithFrame:CGRectMake( 50 , 300 , 200 , 40 )]; firstField.backgroundColor = [UIColor whiteColor]; [self.view addSubview:firstField]; // 添加第一個文本框 UITextField *secondField = [[UITextField alloc]initWithFrame:CGRectMake(firstField.x, firstField.bottom + 50 , firstField.width , firstField.height)]; [self.view addSubview:secondField]; secondField.backgroundColor = [UIColor whiteColor]; // 注冊鍵盤顯示的通知 [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector (showKeyboard:) name:UIKeyboardWillShowNotification object:nil]; // 注冊鍵盤隱藏的通知 [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector (hideKeyboard: ) name:UIKeyboardWillHideNotification object:nil]; } // 鍵盤彈出時執行這個方法, -( void )showKeyboard:(NSNotification *)notification{ // 定義一個文本框,指向正在編輯的文本框,也就是彈出鍵盤的文本框 UITextField *txtField; // 今次遍歷當前視圖的所有子視圖, subViews數組保存的是當前視圖所有的子視圖 for (UIView *subView in self.view.subviews) { // 如果這個子視圖是一個文本框的話,isKindOfClass方法可以判斷某個變量是不是某個類型的變量 if ([subView isKindOfClass:[UITextField class ]]) { // 先把這個子視圖轉化為文本框 UITextField *tempField = (UITextField *)subView; // 再判斷這個文本框是不是正在編輯 if (tempField.isEditing ) { // 如果這個文本框正在編輯,就是我要找的文本框,中斷循環 txtField = tempField; break ; } } } NSLog(@ "%@" , notification); // 獲取通知的userInfo屬性 NSDictionary *userInfoDict = notification.userInfo; // 通過鍵盤通知的userInfo屬性獲取鍵盤的bounds NSValue *value = [userInfoDict objectForKey:UIKeyboardBoundsUserInfoKey]; // 鍵盤的大小 CGSize keyboardSize = [value CGRectValue].size; // 鍵盤高度 CGFloat keyboardHeight = keyboardSize.height; CGFloat offset = kDeviceHeight - keyboardHeight - txtField.bottom ; if (offset < 0 ) { //這種情況下需要上移 offset = offset - 10 ; //保存上移的高度 [UIView animateWithDuration: 0.5 animations:^{ self.view.transform = CGAffineTransformMakeTranslation( 0 , offset ); }]; } } -( void )hideKeyboard:(NSNotification *)notification{ [UIView animateWithDuration: 2 animations:^{ self.view.transform = CGAffineTransformIdentity; }]; } // 點擊屏幕空白時隱藏鍵盤 -( void )touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ [self.view endEditing:YES]; } @end |
關于鍵盤彈出與隱藏代碼就給大家介紹到這里,希望對大家有所幫助!