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

iOS 隐藏键盘,输入法,防止遮挡输入框

2013-03-12 12:16 716 查看
在百度里输入“ios 隐藏键盘”,很快搜出很多文章。比如:“点击return隐藏”,“点击输入框其他地方隐藏”,等等还有的大篇大论的。

其实隐藏输入法也简单,我们应该抓住其本质:即调用resignFirstResponder函数实现隐藏(下面想些介绍)resignFirstResponder

当然,你可以在下面任何一个地方调用,即可隐藏输入法键盘。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

NSLog(@"%@",@"pointer began");
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

NSLog(@"%@",@"pointer move");
[textFieldresignFirstResponder];//滑动时隐藏输入法
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{

NSLog(@"%@",@"pointer end");
}

还有一种方法点击“return”后自动隐藏。注意:这个方法需要继承协议UITextFieldDelegate

只能是UIViewController继承自UITextFieldDelegate才行。UIView类继承UITextFieldDelegate就不行。

还要继续研究,为什么UIView就不行。

(哎太大意了:是因为我的UIView没有实现UITextFieldDelegate协议,加上contentField.delegate = self;就好了)

resignFirstResponder

交出输入法的第一响应者的身份,达到隐藏的目的。待续。。。。。

防止遮挡输入框

以下文章摘自http://xscconan.blog.163.com/blog/static/149593132012111310351998/

主要思想:就是在键盘弹出时候,还有隐藏的时候,相应的view也做出相应上移或者下移的效果:

前提:view实现输入框的协议,contentField.delegate
= self;

//开始编辑输入框的时候,软键盘出现,执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{

int offset =216;//frame.origin.y + 43 - (self.frame.size.height - 216.0);//键盘高度216

//将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示
if(offset >0)
{
NSTimeInterval animationDuration =0.30f;

[UIViewbeginAnimations:@"ResizeForKeyboard"context:nil];
[UIViewsetAnimationDuration:animationDuration];
self.frame =CGRectMake(0.0f, -offset,self.frame.size.width,self.frame.size.height);

[UIViewcommitAnimations];
}
}

//当输入框隐藏时,view也做出相应下移操作
-(void)textFieldDidEndEditing:(UITextField *)textField
{
NSTimeInterval animationDuration =0.30f;

[UIViewbeginAnimations:@"ResizeForKeyboard"context:nil];
[UIViewsetAnimationDuration:animationDuration];

//20是topbar的高度,其实view.frame的size是[0,460].

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

[UIViewcommitAnimations];
}

完美实现。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: