响应键盘事件

通过对键盘事件的响应,让控件不被遮挡。
通过下面第一个方法添加监听,当键盘显示和隐藏的时候会分别调用下面第二和第三个方法,对于界面的定制就写在第二跟第三个方法中。

-(void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:)
name:UIKeyboardDidHideNotification object:nil];
}
-(void)keyboardWasShown:(NSNotification*)noti
{
NSDictionary * info = [noti userInfo];
//UIKeyboardBoundsUserInfoKey Deprecated(已过时)
// NSValue *value = [info objectForKey:UIKeyboardBoundsUserInfoKey];
// CGSize keyboardSize = [value CGRectValue].size;
// CGFloat keyboardHeight = keyboardSize.height;

NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect rect = [value CGRectValue];

//获得的这个rect表示的是在屏幕坐标系统里的键盘的frame,没有考虑任何方向旋转造成的影响,也就是说实际使用中要经过转换,否则可能造成宽度和高度对调
CGRect keyboardFrame = [self.view convertRect:rect fromView:[[UIApplication sharedApplication] keyWindow]];
CGFloat keyboardHeight = keyboardFrame.size.height;
NSLog(@"%f",keyboardHeight);

//让View的高度减少一个键盘的高度
CGRect frame = self.view.frame;
frame.size.height -= keyboardHeight;
self.view.frame = frame;

//如果是ScrollView,还可以让其滚动到指定位置
//......

}
-(void)keyboardWasHidden:(NSNotification*)noti
{
NSDictionary * info = [noti userInfo];
//UIKeyboardBoundsUserInfoKey Deprecated(已过时)
// NSValue *value = [info objectForKey:UIKeyboardBoundsUserInfoKey];
// CGSize keyboardSize = [value CGRectValue].size;
// CGFloat keyboardHeight = keyboardSize.height;

NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect rect = [value CGRectValue];

//获得的这个rect表示的是在屏幕坐标系统里的键盘的frame,没有考虑任何方向旋转造成的影响,也就是说实际使用中要经过转换,否则可能造成宽度和高度对调
CGRect keyboardFrame = [self.view convertRect:rect fromView:[[UIApplication sharedApplication] keyWindow]];
CGFloat keyboardHeight = keyboardFrame.size.height;
NSLog(@"%f",keyboardHeight);

//让View的高度增大一个键盘的高度,回到原高度
CGRect frame = self.view.frame;
frame.size.height += keyboardHeight;
self.view.frame = frame;
}





posted @ 2012-02-14 10:13  Piosa  阅读(641)  评论(0编辑  收藏  举报