您好,登錄后才能下訂單哦!
這篇文章主要介紹了iOS如何實現防鍵盤遮擋,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
當我們在UITextField輸入數據時經常彈出鍵盤遮擋界面,解決方法是:在彈出鍵盤時將整個UIVIew向上移動,在鍵盤消失時,UIVIew還原。
實例代碼如下:
@interface ViewController ()<UITextFieldDelegate> @property(nonatomic,strong)UITextField* tf; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.tf = [[UITextField alloc]initWithFrame:CGRectMake(10, 600, 100, 20)]; self.tf.delegate = self; self.tf.backgroundColor = [UIColor blackColor]; [self.view addSubview:self.tf]; } #pragma mark life Circle -(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; //后臺切換到前臺通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground)name:UIApplicationWillEnterForegroundNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; [self.view endEditing:YES]; } - (void)applicationWillEnterForeground{ [self.view endEditing:YES]; } -(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ [self.view endEditing:YES]; } #pragma mark UITextFieldDelegate -(void)textFieldDidBeginEditing:(UITextField *)textField{ //第一個cell不往上彈輸入框的位置 // if(indexPath.row!=0){ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil]; // } } -(void)textFieldDidEndEditing:(UITextField *)textField{ } #pragma mark 鍵盤操作 - (void)keyboardWillChange:(NSNotification *)note { NSDictionary *userInfo = note.userInfo; CGFloat duration = [userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue]; CGRect keyFrame = [userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue]; //這個64是我減去的navigationbar加上狀態欄20的高度,可以看自己的實際情況決定是否減去; CGFloat moveY = keyFrame.origin.y -self.tf.frame.origin.y-self.tf.frame.size.height; NSLog(@"%f",moveY); [UIView animateWithDuration:duration animations:^{ self.view.transform = CGAffineTransformMakeTranslation(0, moveY); }]; } - (void)keyboardWillHide:(NSNotification *)nsnotification { [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil]; [UIView animateWithDuration:0.2 animations:^{ self.view.transform = CGAffineTransformMakeTranslation(0, 0); }]; } @end
感謝你能夠認真閱讀完這篇文章,希望小編分享的“iOS如何實現防鍵盤遮擋”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。