之前项目中遇到键盘弹出遮挡输入框时, 都是使用三方库DaiDodgeKeyboard进行界面上移动画, 这个三方库很方便, 但是有时候会出现一些莫名的Bug, 所以自己动手实现了一个简单的效果,基本实现了键盘弹出的动画效果, 可能还要具体需求具体分析, 不过一般场景已经够用,
1.添加测试UITextfield,添加一下键盘的通知, 并记得移除
// 添加
- (void)viewDidLoad {
[super viewDidLoad];
elf.view.backgroundColor=[UIColor whiteColor];
//添加UItextfield
_editingTextField=[[UITextField alloc]init];
CGFloat textX =100;
CGFloat textY =500;
CGFloat textW =100;
CGFloat textH =50;
_editingTextField.frame=CGRectMake(textX, textY, textW, textH);
_editingTextField.placeholder=@"测试!!!";
[self.view addSubview:_editingTextField];
[self.editingTextField resignFirstResponder];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
//移除
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
2.写一个方法取到编辑状态下的textfield
- (void)getIsEditingView:(UIView *)rootView {
for (UIView *subView in rootView.subviews) {
if ([subView isKindOfClass:[UITextField class]]) {
if (((UITextField *)subView).isEditing) {
self.editingTextField = (UITextField *)subView;
return;
}
}
[self getIsEditingView:subView];
}
}
3.计算已经拿到的textfield在屏幕中的位置
- (CGFloat)screenViewYValue:(UIView *)textfield {
CGFloat y = 0;
for (UIView *view = textfield; view; view = view.superview) {
y += view.frame.origin.y;
if ([view isKindOfClass:[UIScrollView class]]) {
// 如果父视图是UIScrollView则要去掉内容滚动的距离
UIScrollView* scrollView = (UIScrollView*)view;
y -= scrollView.contentOffset.y;
}
}
return y;
}
4.最后针对拿到的这个位置来进行视图上移处理, 也就是通知执行的方法
- (void)keyboardWillShow:(NSNotification *)noti {
// 拿到正在编辑中的textfield
[self getIsEditingView:self.view];
// textfield的位置
CGFloat viewY = [self screenViewYValue:self.editingTextField];
// 键盘的Y值
NSDictionary *userInfo = [noti userInfo];
NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGFloat keyboardEndY = value.CGRectValue.origin.y;
// 动画
NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
[UIView animateWithDuration:duration.doubleValue animations:^{
if (viewY+50 > keyboardEndY) {
CGRect rect = self.view.frame;
rect.origin.y += keyboardEndY - (viewY+50);
self.view.frame = rect;
}
}];
}
5.键盘收起方法就比较简单了, 直接复位即可
- (void)keyboardWillHide:(NSNotification *)noti {
CGRect rect = self.view.frame;
rect.origin.y = 0;
self.view.frame = rect;
}
有什么不懂的可以留言哦~~