#pragma mark 键盘控制
/**
* 键盘展开/收起时,动态调整当前scrollView高度,避免键盘挡住当前textField。
* @param showKeyboard 键盘是否弹出
* @param UIView 当前textField所在的view,如果是textfield可以更改为uitextfield
*/
- (void)adjustViewForKeyboardReveal:(BOOL)showKeyboard textField:(UIView *)textField
{
// 获取当前scrollView frame,当键盘弹出时,当前scrollView frame上移一定高度。
CGRect scrollFrame = self.container.frame;
// 如果用户通过点击空白区域收起键盘,视图坐标恢复正常。
if (!textField) {
scrollFrame.origin.y = 0;
[self viewChangeOriginYAnimation:scrollFrame];
return;
}
// 键盘弹出,重新计算scrollView y轴。
if (showKeyboard) {
float keyboardHeight = keyboardRect.size.height;
float bottomHeight = kHeightOfMainScreen - CGRectGetMaxY(self.container.frame) + self.container.bounds.size.height - (textField.frame.origin.y - self.container.contentOffset.y)-textField.bounds.size.height;
if (bottomHeight >= keyboardHeight) {
return;
}
// 计算view Y轴位移量,使得弹出键盘和当前textField的距离等于指定值。
scrollFrame.origin.y -= (keyboardHeight-30) + kTextFieldPadding - bottomHeight;
}
// 当键盘收起时,当前视图frame Y轴置为0。
else {
scrollFrame.origin.y = 0;
}
[self viewChangeOriginYAnimation:scrollFrame];
}
/**
* view改变y坐标时,增加动画效果。
* @param viewFrame view视图的新frame
*/
- (void)viewChangeOriginYAnimation:(CGRect)viewFrame
{
// 视图上移/下移动画
[UIView setAnimationDuration:kAnimationDuration];
self.container.frame = viewFrame;
[UIView commitAnimations];
}
/** 键盘弹出通知方法,设置全局弹出键盘fame属性,并动态调整当前scrollView高度。 */
- (void)keyboardWillShow:(NSNotification *)notification
{
// 返回通知关联的用户信息字典,从中取出弹出键盘尺寸信息。
NSDictionary *userInfo = [notification userInfo];
// 取键盘frame的value值,从而获取键盘frame。
NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
keyboardRect = [value CGRectValue];
[self adjustViewForKeyboardReveal:YES textField:self.viewTop];
}
/** 键盘收起通知方法,动态调整当前scrollView高度。 */
- (void)keyboardWillHide:(NSNotification *)notification
{
[self adjustViewForKeyboardReveal:NO textField:self.viewTop];
}
在类中定义全局变量
/** 弹出键盘fame */
CGRect keyboardRect;
// 获取焦点的textfield所在的view
UIView *viewTextField;
使用方式:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
-(void)viewWillDisappear:(BOOL)animated{
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}
/** 处理键盘“return”按钮点击事件 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
[self adjustViewForKeyboardReveal:NO textField:viewTextField];// viewTextField 为textfield所在view
return YES;
}
// 获得焦点
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
if (textField == textfieldAtView.textField) {
viewTextField = textfieldAtView;
}
return YES;
}