5

UIScrollView内部にいくつかの動的ビューがあり、それぞれにテキスト フィールドがあります。ボックスの 1 つに入力を開始するときに、スクロール ビューをスクロールして、フィールドが画面の上部 (キーボードの上に表示される) になるようにします。それはうまくいきます。コードは次のとおりです。

(void)didStartTyping:(id)sender {
    [scrollView setContentOffset:CGPointMake(0, subView.frame.origin.y) animated:YES];
    scrollView.scrollEnabled = NO;
}

(void)didFinishTyping:(id)sender {
    scrollView.scrollEnabled = YES;
}

しかし、スクロール ビューが一番上までスクロールされ、一番下に表示されているテキスト フィールドに入力を開始すると、スクロールが不十分になります (約 40 px 短くなります)。不可解なことは、スクロール ビューの上部から 1 ピクセルだけ下にスクロールすると機能することですが、上にスクロールすると動作が大きく異なります。

4

1 に答える 1

2

これを行うための最良の方法は、キーボード フレームを取得し、テキスト ビューが textViewDidBeginEditing: を呼び出したときにスクロール ビューのインセットを更新することです。ここではテーブルビューを使用していますが、スクロールビューにも同じロジックを適用する必要があります。主な違いはスクロール方法です。私は scrollToRowAtIndexPath を使用します。scrollRectToVisible を使用することをお勧めします。

//setup keyboard callbacks
- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification 
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillHideNotification 
                                               object:nil];
}

- (void)keyboardWillShow:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    kbFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
}

//this is called from your UITextViewDelegate when textViewDidBeginEditing: is called
- (void)updateActiveTextScroll:(UITextView*)textView
{
    activeTextView = textView;
    UIEdgeInsets inset;
    UIInterfaceOrientation orient = [[UIApplication sharedApplication] statusBarOrientation];
    if( UIInterfaceOrientationIsLandscape(orient) )
    {
        inset = UIEdgeInsetsMake(0.0, 0.0, kbFrame.size.width, 0.0);
    }
    else
    {
        inset = UIEdgeInsetsMake(0.0, 0.0, kbFrame.size.height, 0.0);
    }
    myTableView.contentInset = inset;
    myTableView.scrollIndicatorInsets = inset;

    [myTableView scrollToRowAtIndexPath:activeNSIndexPath
                       atScrollPosition:UITableViewScrollPositionBottom
                               animated:YES];
}

//dont forget to reset when the keyboard goes away
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets inset = UIEdgeInsetsZero;
    myTableView.contentInset = inset;
    myTableView.scrollIndicatorInsets = inset;
}
于 2012-09-13T00:12:51.570 に答える