一.简介
1.键盘的例子,键盘inputAccessoryView如何自定义例子。
二.技术要点
1.如何添加键盘监控
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
所有的时间监控都是如此方式。在viewDidUnload对应的要消除监听
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
dealloc中要移除所有监听事件
[[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:nil];
2.添加自定义inputAccessoryView
首先从nib中读取一个view
[[NSBundle mainBundle] loadNibNamed:@"AccessoryView" owner:self options:nil];
设置参数
textView.inputAccessoryView = accessoryView;
3.keyboardWillShow一般是调整view的位置,使得view出现在可见位置,而不是被键盘遮挡住,相对的 keyboardWillHide则恢复状态
4.从notification中获得信息,注意NSValue的用法
- (void)keyboardWillShow:(NSNotification *)notification {
//获得notification信息
NSDictionary *userInfo = [notification userInfo];
//打印信息,里面有很多信息
NSLog(@"%@",userInfo);
// 获得键盘信息
NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
CGFloat keyboardTop = keyboardRect.origin.y;
CGRect newTextViewFrame = self.view.bounds;
newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;
//获得默认动画显示的时间间隔
NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSTimeInterval animationDuration;
[animationDurationValue getValue:&animationDuration];
//设置动画,调整整个textView的frame
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:animationDuration];
textView.frame = newTextViewFrame;
[UIView commitAnimations];
}
keyboardWillShow
keyboardWillShow