记录一下自己经常遇到问题。使用textfield(textview)。当输入框位置比较靠下时,弹出的键盘会遮挡输入框,这是就需要动态移动输入框编辑状态时self.view的位置,
自己经常用的方法有两个
1、项目中很多地方用到输入框,并出现这些问题,用第三方库---IQKeyboardManager,非常的方便,什么都不用写就能实现很多功能。就不详叙述了
2、一两处地方用到,可以自己简单的写一下
两个通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
self.tempTF------定义的中间textfield。当有多个输入框是,在代理中
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
self.tempTF = textField;
return YES;
}
--------------------------------------------------------------------------------------------------------------------------------------------------
/**
* 键盘出现
*/
- (void)keyboardWillShow:(NSNotification *)notification
{
//获取键盘高度,在不同设备上,以及中英文下是不同的
CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
// 取得键盘的动画时间,这样可以在视图上移的时候更连贯
double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGFloat offset = HEIGHT - (self.tempTF.frame.origin.y+self.tempTF.frame.size.height+kbHeight);
if(offset<=0)
{
[UIView animateWithDuration:duration animations:^{
CGRect frame = self.view.frame;
frame.origin.y = offset;
self.view.frame = frame;
}];
}
}
/**
* 键盘消失
*/
- (void)keyboardWillHide:(NSNotification *)notification
{
// 键盘动画时间
double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//视图下沉恢复原状
[UIView animateWithDuration:duration animations:^{
self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}];
}
--------------------------------------------------------------------------------------------------------------------------------------------------
over---新手,有很多不足,敬请见谅。