1、检测视图在窗口中的位置(用于检测键盘的高度)
UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
CGRect rect=[view1 convertRect: view1.bounds toView:window];
2、获取键盘弹出所需时间
//获取键盘弹出时间
NSValue *animationDurationValue = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSTimeInterval animationDuration;
[animationDurationValue getValue:&animationDuration];
实例一:点击TextView或TextFiled 控件随着键盘滚动
在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 *)note
{
NSDictionary *info = [note userInfo];
CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
//目标视图UITextField
UIView *TextViewBGView = [self.view viewWithTag:80];
CGRect frame = TextViewBGView.frame;
int y = frame.origin.y + keyboardSize.height - self.view.frame.size.height+frame.size.height-25;
NSTimeInterval animationDuration = 0.50f;//设置弹出时间慢点,
[UIView beginAnimations:@"ResizeView" context:nil];
[UIView setAnimationDuration:animationDuration];
if(y > 0)
{
self.view.frame = CGRectMake(0, -y, self.view.frame.size.width, self.view.frame.size.height);
}
[UIView commitAnimations];
}
//键盘隐藏后将视图恢复到原始状态
-(void)keyboardWillHide:(NSNotification *)note
{
NSTimeInterval animationDuration = 0.10f;//关闭的时间设置快点
[UIView beginAnimations:@"ResizeView" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations];
}
实例二:点击空白处关闭键盘
在viewDidLoad方法中注册通知
//点击关闭键盘
self.view.userInteractionEnabled = YES;
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
[self.view addGestureRecognizer:singleTap];
-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer{
[self.view endEditing:YES];
}