簡體   English   中英

如何在UITableView中將單元格插入頂部而不移動到頂部偏移

[英]How can insert cells to top in UITableView without moving to top offset

我們可以將單元格插入到UITableView或UICollectionView中,如果將單元格插入到中間或底部,我們將感覺很平滑並保持在當前偏移量。 但是,當我在頂部插入時,tableview或UICollectionView將自動移動到Offset 0(偏移零),這意味着我將不會停留在想要的當前可見單元格上。 我如何實現它,它是本機功能還是我們必須編寫一些復雜的代碼? 我看到了FB Messenger或Skype應用程序,當滾動到頂部時,將插入新消息,而不會更改當前的可見視圖。 有人給我建議解決方案嗎?

如果您使用master-Detail應用程序創建一個新的簡單項目,則可以看到插入時它不會滾動到頂部,即使您位於中間,頂部或底部,內容偏移也只改變了一點(等於新行高)它插入在頂部。 它使用像

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

現在,即使您不希望在此處進行少量滾動也是不錯的解決方案

//just need check if you already on the top of the tableview that may be first few rows depend on your row height 
if(self.tableView.contentOffset.y > ONE_OR_X_ROWS_HEIGHT_YOU_DECIDE
{

    self.delayOffset = self.tableView.contentOffset;
    self.delayOffset = CGPointMake(self.delayOffset.x, self.delayOffset.y+ insertedRowCount * ONE_ROW_HEIGHT);

    //insert your row here 

    [self.tableView setContentOffset:self.delayOffset animated:NO];    


}else
{
    //insert your row here

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM