在一些網站上岸界面,我們常常會面到,鍵盤的湧現與隱蔽操作,那末基於代碼是若何完成的呢?上面小編寫了詳細代碼引見,特此分享到本站平台,供年夜家參考
先給年夜家展現下後果圖:
詳細代碼以下所示:
#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
關於鍵盤彈出與隱蔽代碼就給年夜家引見到這裡,願望對年夜家有所贊助!
【鍵盤彈出時會籠罩文本框怎樣處理】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!