在使用 UITextField 过程中 通常会遇到弹起键盘时候 遮挡住了 textField 的问题这里为了解决这个问题 使用如下方法:(这里是给一个 view 增加一个类别)
/** 监听键盘弹起 设置 view 的偏移 注 : NSNotification 的 name 必须是 : UIKeyboardWillChangeFrameNotification */
- (void)onKeyboardNotification:(NSNotification *)notification;
-
/** 放弃第一响应者 */
-(void)registerFirstResponeder;
实现 :
/** 监听键盘弹起 设置 view 的偏移 注 : NSNotification 的 name 必须是 : UIKeyboardWillChangeFrameNotification */
- (void)onKeyboardNotification:(NSNotification *)notification {
NSAssert([notification.name isEqualToString:UIKeyboardWillChangeFrameNotification], @"NSNotification 的 name 必须是 : UIKeyboardWillChangeFrameNotification");
//
UIView *window = [UIApplication sharedApplication].keyWindow;
float duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
UIView *inputView = [self getInputView:self];
if (!inputView || [inputView isMemberOfClass:NSClassFromString(@"UIWebBrowserView")]) {
return;
}
CGRect rect = CGRectNull;
if (inputView) {
rect = [inputView convertRect:inputView.bounds toView:window];
}
CGRect keyboardFrame = ((NSValue *) notification.userInfo[UIKeyboardFrameEndUserInfoKey]).CGRectValue;
if (keyboardFrame.origin.y == window.height) {
[UIView animateWithDuration:duration animations:^{
self.transform = CGAffineTransformIdentity;
}];
return;
}
if (rect.origin.y+rect.size.height > keyboardFrame.origin.y) {
CGFloat changHeight = rect.origin.y+rect.size.height -keyboardFrame.origin.y;
[UIView animateWithDuration:duration animations:^{
self.transform = CGAffineTransformTranslate(self.transform, 0, -changHeight);
}];
} else {
[UIView animateWithDuration:duration animations:^{
self.transform = CGAffineTransformIdentity;
}];
}
}
/** 递归遍历 textField */
- (UIView *)getInputView:(UIView *)mainView {
if (mainView.isFirstResponder) {
return mainView;
}
if (mainView.subviews.count > 0) {
for (UIView *view in mainView.subviews) {
UIView *tempView = [self getInputView:view];
if (tempView) {
return tempView;
}
}
}
return nil;
}
/** 放弃第一响应者 */
-(void)registerFirstResponeder{
[UIView animateWithDuration:0.25 animations:^{
self.transform = CGAffineTransformIdentity;
}];
}
项目中的使用 :
// - 初始化
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(onKeyboardChangeNoti:) name:UIKeyboardWillChangeFrameNotification object:nil];
/** 键盘变化的通知 */
-(void)onKeyboardChangeNoti:(NSNotification *)noti{
[view onKeyboardNotification:noti];
}
// - 收起键盘
[view registerFirstResponeder];
// - dealloc 时候需要移除通知
[self registerFirstResponeder];