</pre><p></p><div></div><div><pre name="code" class="objc">#pragma mark - 监听键盘高度
-(void)viewWillAppear:(BOOL)animated
{
[self registerForKeyboardNotifications];
}
-(void)viewWillDisappear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)registerForKeyboardNotifications
{
//使用NSNotificationCenter 鍵盤出現時
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
//使用NSNotificationCenter 鍵盤隐藏時
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)name:UIKeyboardWillHideNotification object:nil];
}
//实现当键盘出现的时候计算键盘的高度大小。用于输入框显示位置
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
//kbSize即為鍵盤尺寸 (有width, height)
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//得到鍵盤的高度
NSLog(@"hight_hitht:%f",kbSize.height);
_keyboardhight = kbSize.height;
//输入框位置动画加载
[self begainMoveUpAnimation:kbSize.height];
}
//当键盘隐藏的时候
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
//do something
}
-(void)begainMoveUpAnimation:(CGFloat)keyboardhight{
[UIView animateWithDuration:0.1 animations:^{
self.view.center = CGPointMake(WIDTH/2, HEIGHT/2 + 32 - keyboardhight);
}];
}
#pragma mark- textView Delegate
//开始输入 改变View的高度
- (BOOL)textViewShouldBeginEditing:(UITextField *)textField
{
[self begainMoveUpAnimation:_keyboardhight];
return YES;
}
//输入结束时调用动画(把按键。背景。输入框都移下去)
-(void)textViewDidEndEditing:(UITextView *)textView
{
//释放
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
}