2016-04-29 54 views
6

我在UITableViewCell中有一個按鈕,它存儲爲稱爲currentButton的ivar。單擊該按鈕時,將調用包含UIPickerView和UIToolBar的UIView,並從屏幕底部顯示該UIView。然而,我已經看了幾個小時的其他職位,下面的代碼仍然不起作用。單元格有時在鍵盤下方向下滾動,並且UITableView底部的單元格不會向上滾動到UIView backgroundPickerView頂部。這是我的代碼:滾動UITableViewCell到可見不按預期工作

CGPoint center = currentButton.center; 
    CGPoint rootViewPoint = [currentButton.superview convertPoint:center toView:self.view]; 
    NSIndexPath *indexPath = [measurementTableView indexPathForRowAtPoint:rootViewPoint]; 
    CGRect cellRect = [measurementTableView rectForRowAtIndexPath:indexPath]; 
    if (cellRect.origin.y + cellRect.size.height >= backgroundPickerView.frame.origin.y) { 
     [measurementTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES]; 
     CGPoint offset = measurementTableView.contentOffset; 
     offset.y += ((cellRect.origin.y - cellRect.size.height) - backgroundPickerView.frame.origin.y); 
     [measurementTableView setContentOffset:offset animated:YES]; 
    } 

有沒有人看到我在做什麼錯在這裏?

+0

是self.view和measurementTableView相同的視圖嗎? – wj2061

+0

@ wj2061不,self.view持有measurementTableView –

+0

您是否找到任何解決方案? –

回答

5

此代碼適用於我。採用與此處建議的方法不同的方法,這對我所需要的很有幫助。

CGRect buttonFrame = [currentButton convertRect:currentButton.bounds toView:measurementTableView]; 
NSIndexPath *indexPath = [measurementTableView indexPathForRowAtPoint:buttonFrame.origin]; 
CGRect backPickFrame = [backgroundPickerView convertRect:backgroundPickerView.bounds toView:measurementTableView]; 
if (buttonFrame.origin.y + buttonFrame.size.height >= backPickFrame.origin.y) { 
    measurementTableView.contentInset = UIEdgeInsetsMake(0.0, 0.0, backgroundPickerView.frame.size.height, 0.0); 
    [measurementTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 
} else { 
    [measurementTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES]; 
} 
5

UITableViewCell被重用,保持對UITableViewCell的子視圖的引用不是一個好方法。
如果特殊的UITableViewCell不在UITableView的visibleCells中,則其幀是未定義的。
一種解決方案是:

  1. 創建一個自定義的UITableViewCell具有相同的結構需要。

  2. 保留自定義UITableViewCell的索引路徑的引用。

  3. 使用此indexpath來完成這項工作。

我希望這將工作:

[measurementTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];  
CGPoint offset = measurementTableView.contentOffset;  
offset.y += backgroundPickerView.frame.height; 
3

第一個問題是UITableView的部分鍵盤下隱藏。因此,當您嘗試滾動到底部行時,表格會反彈並且所需的內容不可見。

要解決這個問題,當鍵盤出現/隱藏你有兩個選擇。

  • self.tableView.contentInstet.bottom更新值考慮到鍵盤的尺寸表的
  • 更新幀,如果您正在使用自動佈局的話,最好的方法將更新底部約束的不變部分(IMO這是更好的方法)。

後你做了,你可以這樣做:

CGRect rectToBeVisible = [currentButton convertRect: currentButton.bounds 
              toView: self.tableView]; 
[self.tableView scrollRectToVisible: rectToBeVisible animated: YES]; 

我搞砸了以應進行哪些皈依,所以試驗了一下,但總的概念應該是清楚的。