当键盘出现在我的应用程序中时,我的视图可以向上滑动,因此可以看到文本字段并且效果很好。但是,因为它基于键盘通知,所以它仅在键盘出现时才起作用。
意思是,我选择了一个文本字段,键盘出现并且视图相应地向上滑动,但是如果我直接点击另一个文本字段,则视图不会调整,因为键盘已经存在。
这是我正在使用的代码,任何帮助使其适应上述情况的帮助将不胜感激。
-(void)registerForKeyboardNotifications
{
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[center addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
// add a tap gesture to drop first responder
UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToHideKeyboard:)];
[self.view addGestureRecognizer:tapGR];
}
-(void)keyboardDidShow:(NSNotification *)notification
{
CGRect keyboardFrameW = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
CGRect keyboardFrame = [window convertRect:keyboardFrameW toView:self.view];
//Have a minimum space between the keyboard and textfield
CGFloat textFieldBuffer = 40;
CGFloat textFieldKeyboardDifference = 0;
if (activeTextField.frame.origin.y + activeTextField.frame.size.height > keyboardFrame.origin.y) textFieldKeyboardDifference = (activeTextField.frame.origin.y + activeTextField.frame.size.height + textFieldBuffer) - keyboardFrame.origin.y;
else if (activeTextField.frame.origin.y + activeTextField.frame.size.height < keyboardFrame.origin.y) textFieldKeyboardDifference = 0;
[self translateView:self.view toRect:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - textFieldKeyboardDifference, self.view.frame.size.width, self.view.frame.size.height) withDuration:0.3];
}
-(void)keyboardWillHide:(NSNotification *)notification
{
//Revert to y origin 0
[self translateView:self.view toRect:CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height) withDuration:0.3];
}
编辑:
当这样调用时,我尝试手动调用键盘通知textFieldDidBeginEditing
:
[self keyboardDidShow:[NSNotification notificationWithName:UIKeyboardDidShowNotification object:nil]];
没有运气。该方法被调用,但由于我无法解决的原因没有进行任何调整。