您的位置:首页 > 移动开发 > IOS开发

解决输入框被键盘挡住的问题

2016-08-09 17:33 411 查看

处理键盘挡住输入框的情况

1.代理方法中处理

2.使用通知

代理方法

例如:

//输入,实现视图整体上移
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
CGFloat offset = self.view.frame.size.height - (textField.superview.frame.origin.y+textField.superview.frame.size.height+216+120);
if (offset<=0)
{
[UIView animateWithDuration:0.3 animations:^{
CGRect frame = self.view.frame;
frame.origin.y = offset;
self.view.frame = frame;
}];
}
return YES;
}
... prompt'''


通知方法

例如:

//注册一个通知中心,用来监视键盘
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

//键盘将要出现
- (void)keyboardWillShow:(NSNotification *)noti
{
CGRect keyBoardRect = [noti.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
CGFloat changeY = keyBoardRect.size.height;

//        CGFloat viewHeight = self.view.frame.origin.y;
//判断当软键盘挡住文本框时就把文本内容整体上移,使得键盘可以显示
if (_codeText.frame.origin.y + changeY > FRAMESCREEN.size.height ) {
[UIView animateWithDuration:[noti.userInfo[UIKeyboardAnimationDurationUserInfoKey]floatValue] animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, -changeY);
}];
}
}


//键盘将要隐藏
-(void)keyboardWillHide:(NSNotification*)noti
{
[UIView animateWithDuration:[noti.userInfo[UIKeyboardAnimationDurationUserInfoKey]floatValue] animations:^{
self.view.transform = CGAffineTransformIdentity;
}];

}


- (void)dealloc
{
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
... prompt'''
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息