有关在键盘显示时传递NSNotification以滚动视图的问题

时间:2011-01-07 19:39:20

标签: iphone objective-c

我有一个视图,其中五个UITextField从上到下间隔开。单击文本字段时,键盘会弹出并覆盖底部的两个文本字段。我已经调整了代码,如果您单击底部的两个文本字段之一,视图将向上滚动以便文本字段可见。

我遇到的问题是,当您从第一个文本字段开始并通过文本字段选项卡时,当您到达最后两个文本字段时,视图不会滚动。我已经确定这是因为当我们在第一个文本字段中单击后,在方法之间切换时,我的方法keyboardWillShow永远不再被调用。

我尝试使用textFieldDidBeginEditing方法来确定哪个文本字段现在具有焦点,然后我想再次调用我的keyboardWillShow方法。但是该方法将NSNotification作为参数,并且通过我的所有搜索,我发现您从未真正想要创建NSNotification对象,而是希望使用NSNotificationCenter中的postNotificationName来传递NSNotification对象。我无法让它正常工作。

这是我的相关代码。

- (void) viewWillAppear:(BOOL)animated
{
  [[NSNotificationCenter defaultCenter] addObserver:self    selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:self.view.window];
  [super viewWillAppear:animated];
}

- (void) viewWillDisappear:(BOOL)animated
{
 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
 [super viewWillDisappear:animated];
}

- (void) keyboardWillShow: (NSNotification *)notif
{
 // get our app delegate so we can access currentTextField
 ScrollingAppDelegate *appDelegate = (ScrollingAppDelegate *)[[UIApplication sharedApplication] delegate];
 appDelegate.notif = notif;
 NSDictionary *info = [notif userInfo];
 NSValue *aValue = [info objectForKey: UIKeyboardBoundsUserInfoKey];
 CGSize keyboardSize = [aValue CGRectValue].size;
 float bottomPoint = (appDelegate.currentTextField.frame.origin.y+ appDelegate.currentTextField.frame.size.height+10);
 scrollAmount = keyboardSize.height - (self.view.frame.size.height - bottomPoint);
 if (scrollAmount > 0) 
 {
  moveViewUp = YES;
  [self scrollTheView:YES];
 }
 else 
 {
  moveViewUp = NO;
 }
}

- (void)scrollTheView: (BOOL)movedUp 
{
 [UIView beginAnimations:nil context:NULL];
 [UIView setAnimationDuration:0.3];
 CGRect rect = self.view.frame;
 if (movedUp) 
  {
  rect.origin.y -= scrollAmount;
 }
 else 
  {
  rect.origin.y += scrollAmount;
 }

 self.view.frame = rect;
 [UIView commitAnimations];
}


- (void) textFieldDidBeginEditing:(UITextField *)textField
{
 // declare app delegate so we can access a varibale in it.
 ScrollingAppDelegate *appDelegate = (ScrollingAppDelegate *)[[UIApplication sharedApplication] delegate];

 // set the app delegate variable currentTextField to the textField which just got focus so we can access it
 // in our other method keyboardWillShow
 appDelegate.currentTextField = textField;
  // some how call keyboardWillShow here so the view will scroll to the current text field
}

如果我这样做错了,请告诉我。我一直在网上搜索答案,但到目前为止我都没有找到答案。我发现滚动视图的所有内容只处理一个文本字段,而不是我需要的多个文本字段。

由于

1 个答案:

答案 0 :(得分:1)

我没有将我发现的原始帖子加入书签,但是这里有一个链接到我正在使用的代码snipet:

https://gist.github.com/295089