看了其他人的博客,根據(jù)需求寫(xiě)的:
要實(shí)現(xiàn)的效果就是,如果鍵盤遮住的輸入框,那么要把view上移,所以需要拿到當(dāng)前輸入框的位置,控制器實(shí)現(xiàn)UITextFiled的代理,有一個(gè)代理方法
//開(kāi)始編輯
- (void)textFieldDidBeginEditing:(UITextField*)textField
{
self.tempTextField = textField;
}
當(dāng)點(diǎn)擊輸入框的時(shí)候,拿到這個(gè)輸入框,變成全局變量,在通知的觸發(fā)事件里面,進(jìn)行比較,如果遮住了,就需要view上移一段距離(根據(jù)需求調(diào)節(jié)),當(dāng)鍵盤需要消失的時(shí)候,還需要把view整體降下來(lái)
1.首先注冊(cè)兩個(gè)通知,監(jiān)聽(tīng)鍵盤出現(xiàn)和消失
//注冊(cè)通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
2.接著實(shí)現(xiàn)通知觸發(fā)事件
- 我在這里還定義了一個(gè)view的偏移量offsetY,方便鍵盤回收的時(shí)候,調(diào)節(jié)view的frame.
- 有一個(gè)問(wèn)題就是如果輸入完之后,鍵盤沒(méi)回收,又點(diǎn)擊了另外一個(gè)輸入框,會(huì)出現(xiàn)問(wèn)題,所以我需要做一個(gè)判斷,上一個(gè)鍵盤到底有沒(méi)有回收,如果沒(méi)有,我會(huì)先回收鍵盤,然后根據(jù)第二個(gè)鍵盤調(diào)節(jié)view
#pragma mark--通知事件
- (void)keyboardWillShow:(NSNotification*)noti
{
//根據(jù)當(dāng)前輸入框調(diào)整view
CGFloat textFieldY = kScreenHigh - self.tempTextField.frame.origin.y;
CGFloat textFieldHeight = self.tempTextField.frame.size.height;
NSDictionary* info = [noti userInfo];
CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
//鍵盤高度
CGFloat keyboardHeight = keyboardSize.height;
// NSLog(@"輸入框高度%f鍵盤高度%f",textFieldY - textFieldHeight,keyboardHeight);
//在第二個(gè)鍵盤出來(lái)前,判斷上個(gè)鍵盤的偏移量 ,退回去
if (self.offsetY > 0) {
[UIView animateWithDuration:0.5f delay:0.f usingSpringWithDamping:10.f initialSpringVelocity:1.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
CGRect oldframe = self.view.frame;
oldframe.origin.y += self.offsetY;
self.view.frame = oldframe;
} completion:nil];
self.offsetY = 0;
}
//判斷鍵盤是否擋住輸入框
if (keyboardHeight >= textFieldY) {
// NSLog(@"輸入框高度%f鍵盤高度%f",textFieldY - textFieldHeight,keyboardHeight);
//偏移量 保存下來(lái)
self.offsetY = keyboardHeight - textFieldY + textFieldHeight;
[UIView animateWithDuration:0.5f delay:0.f usingSpringWithDamping:10.f initialSpringVelocity:1.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
CGRect oldframe = self.view.frame;
oldframe.origin.y -= self.offsetY;
self.view.frame = oldframe;
} completion:nil];
}else{
self.offsetY = 0;
}
}
- 還有鍵盤消失的
- (void)keyboardWillHide:(NSNotification*)noti
{
[UIView animateWithDuration:0.5f delay:0.f usingSpringWithDamping:10.f initialSpringVelocity:1.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
CGRect oldframe = self.view.frame;
oldframe.origin.y += self.offsetY;
self.view.frame = oldframe;
} completion:nil];
self.offsetY = 0;
}