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

2018-05-03  本文已影响0人  咖啡绿茶1991

iOS开发中经常会用到输入框UITextField,所以也常会遇到键盘挡住输入框而看不到输入框的内容。

在这里记录一种方法,用UITextField的代理来实现View的上移来解决这个问题。

首先设置UITextField的delegate为self,然后实现以下两个代理方法:

//开始编辑输入框的时候,软键盘出现,执行此事件  

-(void)textFieldDidBeginEditing:(UITextField *)textField  

{  

int offset = _inputView.bottom + 5  - (self.view.frame.size.height - 216.0);//键盘高度216  

NSTimeInterval animationDuration =0.30f;  

[UIView beginAnimations:@"ResizeForKeyboard" context:nil];  

[UIView setAnimationDuration:animationDuration];  

//将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示  

if(offset > 0)  

self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);  

[UIView commitAnimations];  

}  

//输入框编辑完成以后,将视图恢复到原始状态  

-(void)textFieldDidEndEditing:(UITextField *)textField  

{  

self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);  

其中_inputView.bottom是利用第三方库获取控件底部的坐标。这个类库为UIViewExt。

收起键盘的方法见另一篇:iOS隐藏键盘的几种方式

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/u011619283/article/details/38011037

上一篇 下一篇

猜你喜欢

热点阅读