UICollectionView insert cells above maintaining position (like Messages.app)

后端 未结 20 2094
渐次进展
渐次进展 2020-12-02 07:23

By default Collection View maintains content offset while inserting cells. On the other hand I\'d like to insert cells above the currently displaying ones so that they appea

20条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 08:16

    I have used the @James Martin approach, but if you use coredata and NSFetchedResultsController the right approach is store the number of earlier messages loaded in _earlierMessagesLoaded and check the value in the controllerDidChangeContent:

    #pragma mark - NSFetchedResultsController
    
    - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
    {
        if(_earlierMessagesLoaded)
        {
            __block NSMutableArray * indexPaths = [NSMutableArray new];
            for (int i =0; i<[_earlierMessagesLoaded intValue]; i++)
            {
                [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
            }
    
            CGFloat bottomOffset = self.collectionView.contentSize.height - self.collectionView.contentOffset.y;
    
            [CATransaction begin];
            [CATransaction setDisableActions:YES];
    
            [self.collectionView  performBatchUpdates:^{
    
                [self.collectionView insertItemsAtIndexPaths:indexPaths];
    
            } completion:^(BOOL finished) {
    
                self.collectionView.contentOffset = CGPointMake(0, self.collectionView.contentSize.height - bottomOffset);
                [CATransaction commit];
                _earlierMessagesLoaded = nil;
            }];
        }
        else
            [self finishReceivingMessageAnimated:NO];
    }
    

提交回复
热议问题