注册键盘弹出和收起的通知事件
#pragma mark notification 通知管理
/**
* @brief 通知注册
* @return
*/
- (void)registNotification
{
// observe keyboard hide and show notifications to resize the text view appropriately
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
实现收到键盘弹出和收起通知事件的响应事件
#pragma mark --键盘弹出收起管理
-(void)keyboardWillShow:(NSNotification *)note{
CGRect frame = self.textViewFrame;
//获取键盘高度
NSDictionary* info = [note userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
//140是文本框的高度,如果你的文本框高度不一样,则可以进行不同的调整
CGFloat offSet = frame.origin.y + 140 - (self.view.frame.size.height - kbSize.height);
//将试图的Y坐标向上移动offset个单位,以使界面腾出开的地方用于软键盘的显示
if (offSet > 0.01) {
WEAKSELF
[UIView animateWithDuration:0.1 animations:^{
weakSelf.tableView.contentOffset = CGPointMake(0, offSet);
}];
}
}
-(void)keyboardWillHide:(NSNotification *)note{
[UIView animateWithDuration:0.1 animations:^{
self.tableView.contentOffset = CGPointMake(0, 0);
}];
}
多时候,我们有多个输入文本框,在我们的示例中,我们就有两个输入文本框,这时候我们收到通知的时候怎么判断是哪个文本框呢?在前的分析中,我们知道,在发出通知之前,系统会调用输入文本框代理的 textFieldShouldBeginEditing: 方法来判断是否允许编辑,那么我们可以在这个方法中判断是哪一个文本框以及文本框的具体位置等等,然后在键盘弹出时通过为止比较确定是否平移,以及平移的offset。
- (BOOL)textViewShouldBeginEditing:(YYTextView *)textView{
//获取当前输入文本框相对于当前view的位置
self.textViewFrame = [textView convertRect:textView.frame toView:self.view];
return YES;
}
注:相关教程知识阅读请移步到IOS开发频道。










