下面的方法可以获取到设备键盘的高度,能够解决键盘弹出时挡住用户输入界面或按钮,所导致用户体验下降的问题。
1. 注册键盘弹出和退出时的通知监听
/* 增加监听(当键盘出现或改变时) */
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
/* 增加监听(当键盘退出时) */
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
2. 键盘弹出时的事件处理
/**
* 键盘弹出
*/
- (void)keyboardWillShow:(NSNotification *)aNotification {
/* 获取键盘的高度 */
NSDictionary *userInfo = aNotification.userInfo;
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = aValue.CGRectValue;
/* 输入框上移 */
CGFloat padding = 20;
CGRect frame = self.registerButton.frame;
CGFloat height = kScreenHeight - frame.origin.y - frame.size.height;
if (height < keyboardRect.size.height + padding) {
[UIView animateWithDuration:kAnimationDuration animations:^ {
CGRect frame = self.view.frame;
frame.origin.y = -(keyboardRect.size.height - height + padding);
self.view.frame = frame;
}];
}
}
3. 键盘退出时的事件处理
/**
* 键盘退出
*/
- (void)keyboardWillHide:(NSNotification *)aNotification {
/* 输入框下移 */
[UIView animateWithDuration:kAnimationDuration animations:^ {
CGRect frame = self.view.frame;
frame.origin.y = 0;
self.view.frame = frame;
}];
}
将来的你,一定会感激现在拼命的自己,愿自己与读者的开发之路无限美好。
网友评论