TextField的输入框被键盘遮挡住,如何调整TextFiel
新项目中,有一个页面大部分都是TextField输入框,并且已经超过了一屏,填写内容时,键盘容易挡住输入框,很是烦人,研究了好久,找出了一个较为满意的方法,贴出来,大家可以一起看看
我的页面整体是一个scrollview,上面贴了一些view,view上面贴着textfield.
分析: 个人觉得,应该在键盘弹起的时候,测量当前textfield在屏幕中的位置,current_y,及current_height,计算当前键盘的height是否比当前textfield的下方位置要高,如果高的话,则需调整self.view整体位置。上代码:
#import "NewDocuView.h"
#define INTERVAL_KEYBOARD 50.0/H_BASE*SCREEN_H //自定义键盘的缓冲距离
@property (nonatomic,assign)float currentf_heihgt; //当前tf的高度
@property (nonatomic,assign)float currentf_y; //当前tf的y值,方便获得keyborard移动位置计算
1.监听keyboard的弹起和隐藏
NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
[defaultCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[defaultCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
2.获得当前输入框所在的位置
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
//获得控件相对于屏幕的位置,不管控件被包含在哪个视图中。。return YES;
UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
CGRect rect=[textField convertRect: textField.bounds toView:window];
_currentf_y = rect.origin.y;
_currentf_heihgt = textField.frame.size.height;
}
3.键盘的代理方法
#pragma mark - - - -- 监听,键盘显示获得键盘的高度 - - - - -- - - -
- (void)keyboardWillShow:(NSNotification *)aNotification
{
//获取键盘的高度
NSDictionary *userInfo = [aNotification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
keyboardheight = keyboardRect.size.height;
//计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
//如果大于0,则键盘将输入框遮挡,需调节高度,小于0,则不需要调节
//SCREEN_H 为屏幕高度
CGFloat offset = _currentf_y + _currentf_heihgt + INTERVAL_KEYBOARD - (SCREEN_H - keyboard height);
//取得键盘的动画时间,这样可以在视图上移的时候更连贯
double duration = [[aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//将视图上移计算好的偏移
if(offset > 0) {
[UIView animateWithDuration:duration animations:^{
self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
}];
}
#pragma mark - - - -- 监听,键盘消失时 - - - - -- - - -
- (void) keyboardWillHide:(NSNotification *)notify {
NSLog(@"key hidden");
// 键盘动画时间
double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//视图下沉恢复原状
[UIView animateWithDuration:duration animations:^{
self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}];
}