2016-05-27 58 views
0

在聊天應用程序中,我正在實施chat table view之上加載更多按鈕。在重新加載源數據後保持UITableView單元格位置與動態高度單元格iOS

當用戶點擊加載更多的按鈕,舊郵件(加上所有這一切都出現在屏幕上的當前消息)得到數據庫中取出(使用NSFetchedResultsController),然後我呼籲chat table viewreloadData()方法。

我想將tableview的滾動位置設置爲重載表之前的最上一行。

根據消息文本,所有消息單元格都是動態高度。我在故事板上使用auto layout

我的代碼:

let oldContentheight = _chatTableView.contentSize.height 
_chatTableView.reloadData() 
executeOnMain { 
    if self.firstTimeFetching { 
     self.firstTimeFetching = false 
     self.scrollTableToLastRow(withAnimation: false) 
     //this is for going to last cell when we come to chat screen 
    } 
    else { 
     //after pressing load more button 
     let newContentHeight = self._chatTableView.contentSize.height 
     let newOffset = CGPointMake(0, newContentHeight - oldContentheight) 
     self._chatTableView.setContentOffset(newOffset, animated: false) 
    } 
} 

回答

0

首先,財產申報,以節省頂部可見細胞的indexpath

@property(strong,nonatomic) *topVisibleIndexPath; 

然後當您單擊載入更多按鈕,你得到的頂部可見單元格IndexPath並保存

NSArray *visibelIndexpaths = [yourTableView.indexPathsForVisibleRows]; 
if(visibelIndexpaths.count > 0) 
    self.topVisibleIndexPath = [visibelIndexpaths firstObject]; 

rel rel OAD,你調用方法:

[yourTableView scrollToRowAtIndexPath:self.topVisibleIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES]

+0

請檢查我的代碼,添加到問題 – D4ttatraya

+0

如果您加載的數據附加了舊數據,則應該依賴TopCell的INDEXPATH。 你應該檢查變量:var indexPathsForVisibleRows:[NSIndexPath]? {get}和方法:func scrollToRowAtIndexPath(_ indexPath:NSIndexPath, atScrollPosition scrollPosition:UITableViewScrollPosition, animated animated:Bool) –

+0

使用var indexPathsForVisibleRows:[NSIndexPath]? {get}在重載後獲取oldIndexPath,調用方法滾動到滾動到原始索引路徑 –

0

而不是使用reloadData的,可考慮做批量更新reloadData將從您的dataSource中加載新的元素,但它也會產生將scrollView的滾動位置重置爲頂部的副作用。

你想要的是使用這種模式:其中insertRowsAtIndexPaths包含您要添加的新行

tableView.beginUpdates() 
tableView.insertRowsAtIndexPaths([/* new rows here as an array of NSIndexPaths */], withRowAnimation: .Automatic) 
tableView.endUpdates() 

+0

如果只對「insert/delete/reloadRowsAtIndexPaths」進行一次調用,則不需要使用'begin/endUpdates'。 – rmaddy

+0

很高興知道,但是您是否需要它來讓動態單元大小工作而不出現抖動? –

+0

是的,使用'beginUpdates/endUpdates'與其間沒有別的東西是更新行高的好方法。 – rmaddy

相關問題