在IOS开发中,如果输入框(UITextFiled)在界面的下半部分,那么,当键盘出现的时候,势必会挡住输入框,就下下面这样:
这样的效果造成了很不好的用户体验,在这一点上,Android或许就做的好一点,在Android中,只要有输入框的地方,不管EditText处在界面什么位置,只要激发键盘开始输入,系统会自动把EditText至于键盘最上方(有的跟布局有关),这样不会遮挡住用户视线。在IOS中,关于这个问题,我参考了一定的解决方案,并自己总结了一下。
主要功能包括:
- 自适应键盘出现后View的高度调整,防止遮挡输入框
- 点击背景区域关闭键盘
- 响应键盘上Return按钮事件(实现在上下UITextFiled间切换光标)
1.首先在ViewController中实现UITextField的一个Delegate
// ViewController.h
// ResizeView
//
// Created by Ryan Tang on 12-11-20.
// Copyright (c) 2012年 Ericsson Labs. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *userNameText;
@property (weak, nonatomic) IBOutlet UITextField *passwordText;
@end
2.实现UITextFiledDelegate中的协议方法
//UITextField的协议方法,当开始编辑时监听
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
NSTimeInterval animationDuration=0.30f;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
float width = self.view.frame.size.width;
float height = self.view.frame.size.height;
//上移30个单位,按实际情况设置
CGRect rect=CGRectMake(0.0f,-30,width,height);
self.view.frame=rect;
[UIView commitAnimations];
return YES;
}
3.恢复移动的视图的方法
//恢复原始视图位置
-(void)resumeView
{
NSTimeInterval animationDuration=0.30f;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
float width = self.view.frame.size.width;
float height = self.view.frame.size.height;
//如果当前View是父视图,则Y为20个像素高度,如果当前View为其他View的子视图,则动态调节Y的高度
float Y = 20.0f;
CGRect rect=CGRectMake(0.0f,Y,width,height);
self.view.frame=rect;
[UIView commitAnimations];
}
4.点击背景隐藏键盘及响应键盘上Return按键的方法
//隐藏键盘的方法
-(void)hidenKeyboard
{
[self.userNameText resignFirstResponder];
[self.passwordText resignFirstResponder];
[self resumeView];
}
//点击键盘上的Return按钮响应的方法
-(IBAction)nextOnKeyboard:(UITextField *)sender
{
if (sender == self.userNameText) {
[self.passwordText becomeFirstResponder];
}else if (sender == self.passwordText){
[self hidenKeyboard];
}
}
5.指定协议及注册事件
- (void)viewDidLoad
{
[super viewDidLoad];
//指定本身为代理
self.userNameText.delegate = self;
self.passwordText.delegate = self;
//指定编辑时键盘的return键类型
self.userNameText.returnKeyType = UIReturnKeyNext;
self.passwordText.returnKeyType = UIReturnKeyDefault;
//注册键盘响应事件方法
[self.userNameText addTarget:self action:@selector(nextOnKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];
[self.passwordText addTarget:self action:@selector(nextOnKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];
//添加手势,点击屏幕其他区域关闭键盘的操作
UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidenKeyboard)];
gesture.numberOfTapsRequired = 1;
[self.view addGestureRecognizer:gesture];
}
最后运行工程,效果如下:
以上就解决了键盘出现遮挡输入框的问题,同时实现了点按背景取消键盘和响应键盘上Return按钮的功能,以上实现方法不是最好的,只是我解决问题的一种方式,以此记录下来,或许对别人有帮助,也欢迎有更好解决方案的童鞋提出修改意见!
工程源码:下载
加入我们的QQ群或微信公众账号请查看: Ryan's zone公众账号及QQ群
欢迎关注我的新浪微博和我交流:@唐韧_Ryan