0

我在滚动视图中有两个 UITextField。由于键盘的原因,我希望触摸每个 textField 都会向上滚动 scrollView(连同其中的 2 个 textField),并且触摸的字段将位于屏幕顶部。我的 textFieldDidBeginEditing 函数看起来是这样的:

- (void) textFieldDidBeginEditing:(UITextField *)textField {
      CGPoint point = CGPointMake( 0 , textField.center.y - 25  );
    [self setContentOffset:point animated:YES];
}

在编辑一个文本字段并且我正在触摸另一个文本字段时的问题 - 滚动视图向下滚动到 (0,0) 位置。为什么会这样?除了 textFieldDidBeginEditing 函数之外,我在任何其他代码中都没有“setContentOffset”。如何修复它以便触摸其他 textField 会向上滚动滚动视图?

4

2 回答 2

0

尝试这个:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, 216, 0.0);
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;
    CGRect frame = CGRectMake(0, textFieds.frame.origin.y + kOtherViewsHeightWhichMightNotBeInSameViewAsScrollView, 10, 10);

    [self.scrollView scrollRectToVisible:frame] animated:YES];
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;
    return YES;
}

不要忘记将视图控制器设置为文本字段的代表

于 2013-10-07T21:36:35.843 回答
0

使用多个 UITextField 时,声明一个 activeTextField 属性并将其分配给 didBegin 和 didEnd 委托调用会很有帮助

@property (nonatomic, assign) activeTextField;

-(void)textFieldDidBeginEditing:(UITextField *)textField
  {
   self.activeTextField = textField;
  }  
- (void)textFieldDidEndEditing:(UITextField *)textField
  {
    self.activeTextField = nil;
  }

然后将scrollView调整为UITextField

在 viewDidLoad 中添加这个观察者

[[NSNotificationCenter defaultCenter] addObserver:self
                                     selector:@selector(keyboardWasShown:)
                                         name:UIKeyboardDidShowNotification
                                       object:nil];

实现这个方法

#define paddingAboveTextField 20
- (void)keyboardWasShown:(NSNotification *)notification
{
  CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
  UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0);
  scrollView.contentInset = contentInsets;
  scrollView.scrollIndicatorInsets = contentInsets;
  CGRect rectMinusKeyboard = self.view.frame;
  rectMinusKeyboard.size.height -= keyboardSize.height;
 if (!CGRectContainsPoint(rectMinusKeyboard, self.activeTextField.frame.origin) ) {
    CGPoint scrollPoint = CGPointMake(0.0, self.activeTextField.frame.origin.y - (keyboardSize.height-paddingAboveTextField)); 
    [scrollView setContentOffset:scrollPoint animated:YES];
  }
}
于 2013-10-07T21:54:33.197 回答