2012-10-31 72 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

相關問題