【发布时间】:2013-02-09 18:28:44
【问题描述】:
当键盘出现在我的应用程序中时,我的视图可以向上滑动,以便可以看到文本字段并且效果很好。但是,由于它基于键盘通知,因此它仅在键盘出现时才起作用。
意思是,我选择一个文本字段,键盘出现,视图相应地向上滑动,但如果我直接点击另一个文本字段,视图不会调整,因为键盘已经存在。
这是我正在使用的代码,非常感谢任何帮助使其适应上述情况的帮助。
-(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]]; 没有运气。该方法被调用,但由于我无法解决的原因未进行任何调整。
【问题讨论】:
-
(void)textFieldDidBeginEditing:(UITextField *)textField 使用了这个委托方法它会解决你的问题。
标签: iphone objective-c ipad uitextfield uikeyboard