Uicollectionview Insert Cells Above Maintaining Position (Like Messages.App)

Maintain scroll position in UICollectionView when scrolling up

As I commented earlier, it may be better to get the delta from contentSize rather than origin of a specific cell. A suggestion based on your own version:

let previousContentHeight = collectionView.contentSize.height
adapter.performUpdates(animated: false) { [weak self] completed in
guard let strongSelf = self else { return }
let delta = strongSelf.collectionView.contentSize.height - previousContentHeight
strongSelf.collectionView.bounds.origin.y += delta
}

UICollectionView auto scroll to cell at IndexPath

I've found that scrolling in viewWillAppear may not work reliably because the collection view hasn't finished it's layout yet; you may scroll to the wrong item.

I've also found that scrolling in viewDidAppear will cause a momentary flash of the unscrolled view to be visible.

And, if you scroll every time through viewDidLayoutSubviews, the user won't be able to manually scroll because some collection layouts cause subview layout every time you scroll.

Here's what I found works reliably:

Objective C :

- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];

// If we haven't done the initial scroll, do it once.
if (!self.initialScrollDone) {
self.initialScrollDone = YES;

[self.collectionView scrollToItemAtIndexPath:self.myInitialIndexPath
atScrollPosition:UICollectionViewScrollPositionRight animated:NO];
}
}

Swift :

 override func viewWillLayoutSubviews() {

super.viewWillLayoutSubviews()

if !self.initialScrollDone {

self.initialScrollDone = true
self.testNameCollectionView.scrollToItem(at:selectedIndexPath, at: .centeredHorizontally, animated: true)
}

}

UICollectionView insertItemsAtIndexPaths: seems to reload collectionview or autoscrolls to top

I experimented the same problem, by calling "insertItemAtIndexPaths" to increment data into my collectionView.

I noticed two things :
- If you add items AFTER the current visible index path, there's no automatic scroll
- If you add items BEFORE the current visible index path, there's no automatic scroll, like you said, but the contentOffset is kept at the same position, but with different contentSize, because you've just added new items.

To deal with this "side effect", I used the solution mentioned here : UICollectionView insert cells above maintaining position (like Messages.app)

As it's explained in the following post, the "CATransaction.setDisableAction(false)" is the key thing to update smoothly the contentOffset position.

UICollectionView container padding

Please try to put following code inside viewDidLoad():

collectionView!.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

This will add padding to every side of the collectionView.


PS: I know the question is here for a while but it might help somebody ;)



Related Topics



Leave a reply



Submit