当其他textField变为活动状态时,为什么scrollView会向下滚动?

时间:2013-10-07 20:01:51

标签: iphone ios

我在scrollView中有两个UITextField。由于键盘,我希望触摸每个textField将向上滚动scrollView(连同其中的2个textFields),触摸的字段将位于屏幕的顶部。 我的textFieldDidBeginEditing函数看起来如此:

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

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

2 个答案:

答案 0 :(得分: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;
}

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

答案 1 :(得分: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];
  }
}