0

scrollView に 2 つの UITextField があります。キーボードのため、各 textField に触れると scrollView が上にスクロールされ (2 つの textField が一緒に)、タッチされたフィールドが画面の上部に表示されるようにします。私の textFieldDidBeginEditing 関数は次のようになります。

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

1 つの textField の編集中に、他の textField に触れているときの問題 - scrollView が (0,0) の位置までスクロールします。なぜそれが起こるのですか?textFieldDidBeginEditing 関数を除いて、他のコードには「setContentOffset」がありません。他の textField へのタッチが scrollView を上にスクロールするように修正するにはどうすればよいですか?

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 に答える