UICollectionView : Offscreen auto scroll for pagin

2019-08-21 04:31发布

I am trying to scroll UICollectionView which is offscreen in my app, by below code.

int pages = ceil(aCollectionView.contentSize.height / aCollectionView.frame.size.height);

for (int i = 0; i < pages; i ++)
{
     NSArray *sortedVisibleItems = [[aCollectionView indexPathsForVisibleItems] sortedArrayUsingSelector:@selector(compare:)];

     NSIndexPath *lastItem = [sortedVisibleItems lastObject];

     // 2.next position
     NSInteger nextItem = lastItem.item + 1;
     NSInteger nextSection = lastItem.section;
     NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];

     [self takeImage];

     dispatch_async(dispatch_get_main_queue(), ^
    {            
        [aCollectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
    });
}

And taking screen shots of each page for printing purpose. But its not scrolling and always prints the 1st page multiple times.

UICollectionView's property

enter image description here

Am I missing or doing in wrong direction ?

3条回答
ら.Afraid
2楼-- · 2019-08-21 05:11

You are always getting last object by NSIndexPath *lastItem = [sortedVisibleItems lastObject]; to take a image. This will only capture same page always.

This is because you are not removing lastObject from your array.

Remove your lastObject by using

[sortedVisibleItems removeLastObject];
查看更多
forever°为你锁心
3楼-- · 2019-08-21 05:11
int pages = ceil(aCollectionView.contentSize.height / aCollectionView.frame.size.height);
NSArray *visibleItems = [aCollectionView indexPathsForVisibleItems];
NSInteger row = 0;
NSIndexPath *currentItem;
for (NSIndexPath *indexPath in visibleItems) {
    if (row < indexPath.row){
        row = indexPath.row;
        currentItem = indexPath;
    }
}
NSLog(@"current indexpath ; %ld",(long)currentItem.row);
if (currentItem.row == pages-1) {
    return;
}
NSIndexPath *nextItem = [NSIndexPath indexPathForItem:currentItem.item + 1 inSection:currentItem.section];
[aCollectionView scrollToItemAtIndexPath:nextItem atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:YES];

Try this

查看更多
何必那么认真
4楼-- · 2019-08-21 05:19

A collection view only updates on the main thread. Your code is wrapped in a loop, which never allows the main thread to run and update.

There are lots of discussions about this out there. Many related directly to doing the same thing with UIScrollView, but it's the same issue.

You might want to look at this... not sure if it will fit your needs, but I've seen it referenced multiple times: https://github.com/sgr-ksmt/PDFGenerator

If that doesn't work for you, it probably has the technique you need in it, so a little investigating of that code should find your answer.

查看更多
登录 后发表回答