解决思路:有时用户编辑输入框时,键盘会遮挡输入框,这时候只要将视图整体上移键盘的高度即可,编辑完成后再将视图下移键盘的高度恢复正常显示。
【方法1】
实现UITextField代理UITextFieldDelegat的两个方法textFieldShouldBeginEditing和textFieldShouldEndEditing,分别在开始输入和结束输入时,将UIView上移或下移恢复。
代码:
.h文件
@interface ViewController : UIViewController<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextView *textField;
@end
.m文件
设置UITextView实例的代理:
_textField.delegate=self
实现代理方法:
-(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;
//上移n个单位,按实际情况设置
CGRect rect=CGRectMake(0.0f,-130,width,height);
self.view.frame=rect;
[UIView commitAnimations];
return YES;
}
- (BOOL)textFieldShouldEndEditing:(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;
//上移n个单位,按实际情况设置
self.view.frame = CGRectMake(0.0f, 130, width, height);
[UIView commitAnimations];
return YES;
}
【方法2】(推荐)
注册键盘弹出和关闭的系统通知,对视图进行整体移动
1、在viewDidLoad中注册通知:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
-(void)keyboardWillShow:(NSNotification*)notification
{
NSDictionary *info = [notification userInfo];
//获取键盘的size值
CGRect _keyBoard = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
//动画时间
NSTimeInterval animationDuration =
[[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//上移n个单位,按实际情况设置
[UIView animateWithDuration:animationDuration animations:^{
CGRect rect = CGRectMake(0.0f,-_keyBoard.size.height,self.view.frame.size.width,self.view.frame.size.height);
self.view.frame=rect;
}];
}
- (void)keyboardWillHide:(NSNotification *)notification
{
//动画时间
NSDictionary *info = [notification userInfo];
NSTimeInterval animationDuration =
[[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//还原输入view位置
[UIView animateWithDuration:animationDuration animations:^{
self.view.frame = CGRectMake(0, 0,self.view.frame.size.width,self.view.frame.size.height);
}];
}
3、在dealloc中注销通知监听
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}