tableView 或 collectionView 最底部插入cell,自動滑動到最底部
正確執行辦法:
[_collection performBatchUpdates:^{
[_collection insertItemsAtIndexPaths:@[idx]];
} completion:^(BOOL finished) {
if (finished)
[self.collection scrollToItemAtIndexPath:[idx indexPathByAddingIndex:1] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:1];
}];
插入後滑動到最底部
分析原因,insert 後直接 scroll,爲什麼不會滑到最底部呢?
調用這兩個函數,分別提交各自的任務。提交的兩個任務會在 runloop 下一圈裏進行 (before waiting 階段)(兩個任務是在一個 runloop 裏提交的)
下一圈 runloop 裏,發現需要 insert,好的,開始 insert 動畫;
緊接着發現要 scroll (可以理解爲“同時”),而此時 insert 動畫剛開始,collectionView 在這一瞬間 ,底部實際上是沒有多出空間的,仍然是 insert 動畫開始時的狀態,也就是說,scroll 動作剛開始就發現已經達到完成狀態了,直接結束。
因此想辦法讓 insert 完成後,回調執行 scroll,但是並沒有發現插入回調的 API,恰好 performBatchUpdates 有回調,那就用咯。