【发布时间】:2011-09-02 14:32:51
【问题描述】:
在我的第一个视图上设法得到它,但在第二个视图上不起作用。
这是我在两个视图上所做的,只是在控制台中用于调试目的略有不同
-(void) viewWillAppear:(BOOL)animated {
//---registers the notifications for keyboard---
// to see if keyboard is shown / not shown
[[NSNotificationCenter defaultCenter]
addObserver: self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:self.view.window];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(keyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
}
//---when the keyboard appears---
-(void) keyboardDidShow:(NSNotification *) notification {
if (keyboardIsShown) return;
NSLog(@"Keyboard is visible 1"); // debugger purpose "Keyboard is visible 2" on the second view.
NSDictionary* info = [notification userInfo];
//---obtain the size of the keyboard---
NSValue *aValue =
[info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect =
[self.view convertRect:[aValue CGRectValue] fromView:nil];
//---resize the scroll view (with keyboard)---
CGRect viewFrame = [scrollview frame];
NSLog(@"%f", viewFrame.size.height);
viewFrame.size.height -= keyboardRect.size.height;
scrollview.frame = viewFrame;
NSLog(@"%f", keyboardRect.size.height);
NSLog(@"%f", viewFrame.size.height);
//---scroll to the current text field---
CGRect textFieldRect = [currentTextField frame];
[scrollview scrollRectToVisible:textFieldRect animated:YES];
keyboardIsShown = YES;
}
//---when the keyboard disappears---
-(void) keyboardDidHide:(NSNotification *) notification {
NSDictionary* info = [notification userInfo];
//---obtain the size of the keyboard---
NSValue* aValue =
[info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect =
[self.view convertRect:[aValue CGRectValue] fromView:nil];
//---resize the scroll view back to the original size
// (without keyboard)---
CGRect viewFrame = [scrollview frame];
viewFrame.size.height += keyboardRect.size.height;
scrollview.frame = viewFrame;
keyboardIsShown = NO;
}
//---before the View window disappear---
-(void) viewWillDisappear:(BOOL)animated {
//---removes the notifications for keyboard---
[[NSNotificationCenter defaultCenter]
removeObserver: self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
}
【问题讨论】:
-
您看到的错误行为是什么?
-
我尝试在调试器控制台中测试输出。我在我的 secondview 上删除了 NSLog。但是当键盘出现在两个视图中时,它会一直显示 3 行。
-
简单来说,当键盘出现在第二个视图时,输出NSLog(@"Keyboard is visible 1");而不是 NSLog(@"Keyboard is visible 2");
-
我认为这可能是我加载视图 2 的方式,因为当我导航到视图 2 时未执行 viewDidLoad 方法。以前使用
codeRegisters *registerview = [[Registers alloc] initWithNibName :nil 捆绑:nil]; [self presentModalViewController:registerview Animation:YES]; -
@Deepak 然后我改为使用 [self presentModalViewController:registerview animated:YES];反而。 view2 的 ViewDidLoad 已执行,并且启用了滚动,但出现了一些问题。当键盘出现在 view2 中时,keyboardDidShow 方法在 view1 和 view2 上都被触发。控制台输出如下“Keyboard is visible 1 & Keyboard is visible 2”
标签: xcode view keyboard scroll