博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS 键盘遮挡输入框的解决方案
阅读量:7102 次
发布时间:2019-06-28

本文共 9954 字,大约阅读时间需要 33 分钟。

hot3.png

1、

第三方:TPKeyboardAvoiding或者防止键盘挡住输入框- (void)viewDidLoad{	//注册监听,防止键盘遮挡视图   	 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];   	 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];}- (void)viewDidDisappear:(BOOL)animated{    [super viewDidDisappear:animated];        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];}- (void) dealloc{    [[NSNotificationCenter defaultCenter] removeObserver:selfname:nilobject:nil];}#pragma mark - textField- (void)textFieldDidBeginEditing:(UITextField *)textField{    top = self.mainTableView.contentOffset.y;//该输入框的偏移量    clickFlg = textField.tag;//判断点击了哪个输入框}#pragma mark - 监听- (void)keyboardWillShow:(NSNotification *)notification {        /*     Reduce the size of the text view so that it's not obscured by the keyboard.     Animate the resize so that it's in sync with the appearance of the keyboard.     */    NSDictionary *userInfo = [notification userInfo];        // Get the origin of the keyboard when it's displayed.    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.    CGRect keyboardRect = [aValue CGRectValue];    keyboardRect = [self.viewconvertRect:keyboardRect fromView:nil];        CGFloat keyboardTop = keyboardRect.origin.y;    CGRect newTextViewFrame = self.view.bounds;    newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;        // Get the duration of the animation.    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];    NSTimeInterval animationDuration;    [animationDurationValue getValue:&animationDuration];    animationDuration += 0.1f;    // Animate the resize of the text view's frame in sync with the keyboard's appearance.    [UIView beginAnimations:nil context:NULL];    [UIViewsetAnimationDuration:animationDuration];        CGFloat clickTop = 0;    //64:顶部高度    clickTop = CGRectGetHeight(self.mainTableView.tableHeaderView.frame) + [self tableView:self.mainTableView heightForRowAtIndexPath:[NSIndexPath indexPathForRow:clickFlg inSection:0]]*(clickFlg+1) + 64;    if (keyboardTop > 0 && keyboardTop < clickTop) {        [self.mainTableViewsetContentOffset:CGPointMake(0, fabsf(keyboardTop - clickTop)) animated:YES];    }        //[self.mainScrollView setContentOffset:CGPointMake(0, keyboardTop) animated:YES];    [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:self.view cache:YES];        [UIView commitAnimations];}- (void)keyboardWillHide:(NSNotification *)notification {        NSDictionary* userInfo = [notification userInfo];        /*     Restore the size of the text view (fill self's view).     Animate the resize so that it's in sync with the disappearance of the keyboard.     */    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];    NSTimeInterval animationDuration;    [animationDurationValue getValue:&animationDuration];        [UIView beginAnimations:nil context:NULL];    [UIViewsetAnimationDuration:animationDuration];        [self.mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];    [UIView commitAnimations];}

2、

// 点击背景退出键盘    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backupgroupTap:)];    tapGestureRecognizer.numberOfTapsRequired = 1;    [self.view addGestureRecognizer: tapGestureRecognizer];   // 只需要点击非文字输入区域就会响应    [tapGestureRecognizer setCancelsTouchesInView:NO];-(void)backupgroupTap:(id)sender{    [self.phoneField resignFirstResponder];}**********************************************************************************************************************************    CGFloat _bottom;    CGPoint _oldOffset;    CGFloat _keyboardTop;#pragma mark - 键盘遮挡输入框处理// 监听键盘弹出通知- (void) registerForKeyboardNotifications {    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];}- (void)unregNotification {    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];}// 开始编辑输入框,获得输入框底部在屏幕上的绝对位置-(void)textFieldDidBeginEditing:(UITextField *)textField {    [self registerForKeyboardNotifications];    UIWindow *window=[[[UIApplication sharedApplication] delegate] window];    CGRect rect=[textField convertRect: textField.bounds toView:window]; // 在屏幕上的坐标    _bottom = rect.origin.y + rect.size.height; // 获得输入框底部在屏幕上的绝对位置}// 键盘弹出,获得键盘高度,计算界面需要偏移的距离- (void) keyboardWillShow:(NSNotification *) notification {    _oldOffset = self.mainScrollView.contentOffset;    [self unregNotification];    NSDictionary *userInfo = [notification userInfo];        // Get the origin of the keyboard when it's displayed.    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.    CGRect keyboardRect = [aValue CGRectValue];    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];    _keyboardTop = keyboardRect.origin.y;        // 计算出需要偏移的距离offset,即输入框bottom与键盘top的距离    float offset = _bottom - _keyboardTop;    if(offset > 0) { // offset为正,说明输入框被键盘遮挡        NSTimeInterval animationDuration = 0.3f;        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];        [UIView setAnimationDuration:animationDuration];        offset += 5;        self.mainScrollView.contentOffset = CGPointMake(0, _oldOffset.y + offset);        [UIView commitAnimations];    }}//键盘隐藏,将视图恢复到原始状态- (void) keyboardWillHidden:(NSNotification *) notif {    self.mainScrollView.contentOffset = _oldOffset;}

3、

- (void)viewDidAppear:(BOOL)animated{    [super viewDidAppear:animated];        //add notification    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillShowNotification object:nil];    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillHideNotification object:nil];    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];}- (void)viewWillDisappear:(BOOL)animated{    [super viewWillDisappear:animated];    [[NSNotificationCenter defaultCenter]removeObserver:self];}-(void)keyboardChange:(NSNotification *)notification{    NSDictionary *userInfo = [notification userInfo];    NSTimeInterval animationDuration;    UIViewAnimationCurve animationCurve;    CGRect keyboardEndFrame;        [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];        [UIView beginAnimations:nil context:nil];    [UIView setAnimationDuration:animationDuration];    [UIView setAnimationCurve:animationCurve];        //adjust ChatTableView's height    if (notification.name == UIKeyboardWillShowNotification || notification.name == UIKeyboardWillChangeFrameNotification) {        self.bottomConstraint.constant = keyboardEndFrame.size.height;    }else{        self.bottomConstraint.constant = 0;    }        [self.view layoutIfNeeded];        //adjust UUInputFunctionView's originPoint    CGRect newFrame = self.viewPing.frame;    newFrame.origin.y = keyboardEndFrame.origin.y - newFrame.size.height;    self.viewPing.frame = newFrame;        [UIView commitAnimations];    }

这是写的一个很简单的例子

#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    self.loginBtn.layer.cornerRadius=4.0;    self.loginBtn.backgroundColor=[UIColor colorWithRed:248.0/255 green:181.0/255 blue:18.0/255 alpha:1];    self.bgview.userInteractionEnabled=YES;    UITapGestureRecognizer *singalTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backKeyboard)];    [self.view addGestureRecognizer:singalTap];    self.password.tag=0;    [self.password addTarget:self action:@selector(textFieldDidBeginEditing:) forControlEvents:UIControlEventEditingDidBegin];        [self.password addTarget:self action:@selector(textFieldDidEndEditing:) forControlEvents:UIControlEventEditingDidEnd];            // Do any additional setup after loading the view, typically from a nib.}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}-(void)backKeyboard{    [self.bgview endEditing:YES];}-(void)textFieldDidBeginEditing:(UITextField *)textField{    if (textField.tag==0) {        [self moveView:-68];    }    }-(void)textFieldDidEndEditing:(UITextField *)textField{    if (textField.tag==0) {        [self moveView:68];    }    }-(void)moveView:(float )move{    NSTimeInterval animationDuration=0.30f;    CGRect frame=self.bgview.frame;    frame.origin.y+=move;    [UIView beginAnimations:@"ResizeViewFrame" context:nil];    [UIView setAnimationDuration:animationDuration];    self.bgview.frame=frame;    [self.bgview layoutIfNeeded];    [UIView commitAnimations];  }@end

转载于:https://my.oschina.net/u/1778933/blog/514131

你可能感兴趣的文章
ThinkphpCMF笔记
查看>>
git分支的合并
查看>>
maven 常用命令
查看>>
小程序五:组件之视图容器
查看>>
H5版俄罗斯方块(5)---需求演进和产品迭代
查看>>
Java多线程有哪几种实现方式? Java中的类如何保证线程安全? 请说明ThreadLocal的用法和适用场景...
查看>>
工作队列(workqueue) create_workqueue/schedule_work/queue_work
查看>>
size_t、ptrdiff_t【转】
查看>>
Python第十三天 django 1.6 导入模板 定义数据模型 访问数据库 GET和POST方法 SimpleCMDB项目 urllib模块 urllib2模块 ...
查看>>
linux运维常见英文报错中文翻译(菜鸟必知)
查看>>
【Linux】查看所使用的Linux系统是32位还是64 位的方法
查看>>
NSJSONSerialization 反序列化失败 NSCocoaErrorDomain Code=3840
查看>>
理解闭包 js回收机制
查看>>
par函数pch参数-控制点的形状
查看>>
MySQL具体解释(8)----------MySQL线程池总结(二)
查看>>
chrome 谷歌浏览器插件损坏
查看>>
前端知识十分钟预览之学习札记
查看>>
ArcGIS API for Silverlight 当DataGrid选中项时,地图聚焦弹出窗口,并可以播放音频文件...
查看>>
JavaWeb学习总结(十三)——使用Session防止表单重复提交
查看>>
C# Qrcode生成二维码支持中文,带图片,带文字 2015-01-22 15:11 617人阅读 评论(1...
查看>>