5

我有一个UIScrollView里面有几个动态视图,每个视图都有一个文本字段。当我开始在其中一个框中输入内容时,我希望滚动视图滚动,以使该字段位于屏幕顶部(在键盘上方可见)。效果很好;这是代码:

(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 像素)。令人费解的是,如果我从滚动视图的顶部向下滚动一个像素,它就可以工作,但是当我向上滚动到顶部时,它的行为就大不相同了。

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 回答