2012-10-31 139 views
5

我有一个UITableView,它比self.view稍大。我在视图的底部有一个UITextField,我使用代理方法– textFieldDidBeginEditing:在文本字段开始编辑时向上移动视图。设置UITableView contentOffset,然后拖动,查看偏移量跳转到新位置

这可以正常工作,但是如果我在编辑UITextField时尝试滚动视图(并且内容已经偏移),那么内容将跳转到视图底部“适当”的位置。换句话说,我设置的contentOffset.y更改为等于内容视图的大小(正如您对正常行为的期望值)。

任何想法如何在编辑时重载此行为?

- (void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
    // Scroll to the currently editing text field 
    [self scrollViewToTextField:textField]; 

} 

- (void)scrollViewToTextField:(id)textField 
{ 
    // Set the current _scrollOffset, so we can return the user after editing 
    _scrollOffsetY = self.tableView.contentOffset.y; 

    // Get a pointer to the text field's cell 
    UITableViewCell *theTextFieldCell = (UITableViewCell *)[textField superview]; 

    // Get the text fields location 
    CGPoint point = [theTextFieldCell convertPoint:theTextFieldCell.frame.origin toView:self.tableView]; 

    // Scroll to cell 
    [self.tableView setContentOffset:CGPointMake(0, point.y - 12) animated: YES]; 
} 

回答

12

避免此行为的方法是同时应用contentInset。因此,对于上面的例子:

- (void)scrollViewToTextField:(id)textField 
{ 
    // Set the current _scrollOffset, so we can return the user after editing 
    _scrollOffsetY = self.tableView.contentOffset.y; 

    // Get a pointer to the text field's cell 
    UITableViewCell *theTextFieldCell = (UITableViewCell *)[textField superview]; 

    // Get the text fields location 
    CGPoint point = [theTextFieldCell convertPoint:theTextFieldCell.frame.origin toView:self.tableView]; 

    // Scroll to cell 
    [self.tableView setContentOffset:CGPointMake(0, point.y - 12) animated: YES]; 

    // Add some padding at the bottom to 'trick' the scrollView. 
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, point.y - 60, 0)]; 
} 

然后务必编辑后到嵌入复位:

- (void)textFieldDidEndEditing:(UITextField *)textField { 
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)]; 
} 

这种方法的条件是,你必须实现在- (void)scrollViewDidScroll:(UIScrollView *)scrollView方法的一些检查,以检查您的文本字段仍在查看中。

此替代方法是在编辑开始时禁用滚动,并在其结束时重新启用滚动。您必须决定此操作是否对您的应用程序中的UX有害。

1

我想补充一点,如果你使用输入文本框。而需要滚动然后应用firstResponder,申请使用EdgeInset:

[self.tableView setContentOffset:CGPointMake(0.0f, 0.0f) animated:YES]; 
[self.tableView setContentInset:UIEdgeInsetsZero]; 

后停止自动滚动时,他们得到的焦点,随着内的UITableView输入字段发生。谢谢@squarefrog

相关问题