1、在viewDidLoad方法中加入监测键盘的通知。
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
}
2、移除通知
-(void)dealloc
{
//第一种方法.这里可以移除该控制器下的所有通知
//移除当前所有通知
NSLog(@"移除了所有的通知");
[[NSNotificationCenter defaultCenter] removeObserver:self];
//第二种方法.这里可以移除该控制器下名称为tongzhi的通知
//移除名称为tongzhi的那个通知
NSLog(@"移除了名称为tongzhi的通知");
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"tongzhi" object:nil];
}
3、实现通知的方法
/**
* 键盘将要显示
*
* @param notification 通知
*/
-(void)keyboardWillShow:(NSNotification *)notification
{
//这样就拿到了键盘的位置大小信息frame,然后根据frame进行高度处理之类的信息
CGRect frame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat endHeight = self.showScrollView.contentSize.height + frame.size.height;
self.showScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, endHeight);
self.showScrollView.contentOffset = CGPointMake(0, self.bottomView.originY);
}
/**
* 键盘将要隐藏
*
* @param notification 通知
*/
-(void)keyboardWillHidden:(NSNotification *)notification
{
CGRect frame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat endHeight = self.showScrollView.contentSize.height - frame.size.height;
self.showScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, endHeight);
}