1 --- 弹出键盘屏幕上移
#pragma mark --弹出键盘移动输入框
- (void)viewDidLoad {
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotificationobject:nil];
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotificationobject:nil];
}
//键盘收起
- (void)keyboardWillHide:(NSNotification*)noti {
CGRectrect =self.view.frame;
rect.origin.y=0;
self.view.frame= rect;
}
//视图上移
- (void)keyboardWillShow:(NSNotification*)noti {
//拿到正在编辑中的textfield
[selfgetIsEditingView:self.view];
// textfield的位置
CGFloatviewY = [selfscreenViewYValue:self.editingTextField];
//键盘的Y值
NSDictionary*userInfo = [notiuserInfo];
NSValue*value = [userInfoobjectForKey:UIKeyboardFrameEndUserInfoKey];
CGFloatkeyboardEndY = value.CGRectValue.origin.y;
//动画
NSNumber*duration = [userInfoobjectForKey:UIKeyboardAnimationDurationUserInfoKey];
[UIViewanimateWithDuration:duration.doubleValueanimations:^{
if(viewY+30> keyboardEndY) {
CGRectrect =self.view.frame;
rect.origin.y+= keyboardEndY - (viewY+50);
self.view.frame= rect;
}
}];
}
//计算textfield的位置
- (CGFloat)screenViewYValue:(UIView*)textfield {
CGFloaty =0;
for(UIView*view = textfield; view; view = view.superview) {
y += view.frame.origin.y;
if([viewisKindOfClass:[UIScrollViewclass]]) {
//如果父视图是UIScrollView则要去掉内容滚动的距离
UIScrollView* scrollView = (UIScrollView*)view;
y -= scrollView.contentOffset.y;
}
}
returny;
}
//取得正在编辑的textfield
- (void)getIsEditingView:(UIView*)rootView {
for(UIView*subViewinrootView.subviews) {
if([subViewisKindOfClass:[UITextFieldclass]]) {
if(((UITextField*)subView).isEditing) {
self.editingTextField= subView;
return;
}
}
[selfgetIsEditingView:subView];
}
}
//移除通知
- (void)dealloc {
[[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardWillShowNotificationobject:nil];
[[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardWillHideNotificationobject:nil];
}