我的应用程序中有一个功能可以在显示键盘时向上移动视图。不幸的是,有一个错误;第一次加载视图时一切正常,但如果切换到另一个视图,然后切换回来,视图不再移动:(
我在代码中添加了一些NSLog
语句来尝试跟踪问题。我正在使用 NSNotification,这很好,因为每次都会调用该方法。
然后我想可能是视图的坐标有问题,所以我添加了打印出视图原点的语句。他们打印出正确的原点(“移动”的原点),即使视图肯定没有移动。
所以看起来 Xcode 认为它已经移动了视图,但它没有。有没有其他人遇到过这种行为?
编辑:这是一些代码
设置通知:
//register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:self.view.window];
//if the keyboard is already being shown because someone was entering a comment, and then they switch to a textfield, this will move the view back down.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UITextFieldTextDidBeginEditingNotification object:self.view.window];
//hide the keyboard
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:self.view.window];
//hide the keyboard if we're done with the textview
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UITextViewTextDidEndEditingNotification object:self.view.window];
keyboardIsShown = FALSE;
tempDelegate.keyboardIsInitialized = TRUE;
显示键盘和移动视图的方法:
-(void)keyboardWillShow:(NSNotification *)notif{
NSLog(@"keyboardWillShow");
NSLog(@"type: %@, keyboardIsShown: %@", sender, keyboardIsShown);
//double check
if (keyboardIsShown || !sender) {
NSLog(@"return");
return;
}
//only adjust screen for comment box (which is a textview)
if(![sender isEqualToString:@"text field"] && [sender isEqualToString:@"text view"]){
NSLog(@"if");
NSDictionary* userInfo = [notif userInfo];
// get the size of the keyboard
CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
[UIView beginAnimations:@"ResizeForKeyboard" context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3];
NSLog(@"regular BEFORE: %@", NSStringFromCGRect(regularView.frame));
regularView.frame = CGRectMake(0, - keyboardSize.height, CGRectGetWidth(imageView.bounds)*scrollView.zoomScale, CGRectGetHeight(imageView.bounds)*scrollView.zoomScale);
NSLog(@"regular AFTER: %@", NSStringFromCGRect(regularView.frame));
[UIView commitAnimations];
keyboardIsShown = YES;
}
}
以及隐藏键盘并将视图移回的方法:
-(void)keyboardWillHide:(NSNotification *)notif{
NSLog(@"keyboardWillHide");
if (!keyboardIsShown) {
NSLog(@"return");
return;
}
[UIView beginAnimations:@"ResizeForKeyboard" context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3];
NSLog(@"regular BEFORE: %@", NSStringFromCGRect(regularView.frame));
self.regularView.frame = CGRectMake(0, 0, CGRectGetWidth(imageView.bounds)*scrollView.zoomScale, CGRectGetHeight(self.imageView.bounds)*scrollView.zoomScale);
[UIView commitAnimations];
NSLog(@"regular AFTER: %@", NSStringFromCGRect(regularView.frame));
keyboardIsShown = NO;
}