I'm sometimes scroll to the left of a cell like this:
collectionView.scrollToItem(
at: IndexPath(row: 5, section: 0),
at: .left, // TODO: Left ignores inset
animated: true
)
This is how it starts out before scrollToItem
implemented:
However, when I try to use scroll to item, it sticks the cell to the edge instead of considering the inset:
Is there an easy way to fix collectionView.scrollToItem
to accommodate the insets?
You can use the regular method collectionView.scrollToItem
if you set your inset in collectionView.contentInset
instead of layout.sectionInset
.
Objective-C
/**
Assumptions:
1. Your collection view scrolls horizontally
2. You are using UICollectionViewFlowLayout to layout you collection view
@param indexPath IndexPath to scroll to
@param animated Toggle animations
*/
- (void)scrollToIndexPathPreservingLeftInset:(NSIndexPath *)indexPath animated:(BOOL)animated {
UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)collectionView.collectionViewLayout;
CGFloat sectionLeftInset = layout.sectionInset.left;
UICollectionViewLayoutAttributes *attri = [layout layoutAttributesForItemAtIndexPath:indexPath];
[collectionView setContentOffset:CGPointMake(attri.frame.origin.x - sectionLeftInset, 0) animated:animated];
}
Swift (not verified syntactically)
func scroll(toIndexPathPreservingLeftInset indexPath: IndexPath, animated: Bool) {
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let sectionLeftInset = layout.sectionInset.left
var attri = layout.layoutAttributesForItem(at: aPath)
collectionView.setContentOffset(CGPoint(x: (attri?.frame.origin.x - sectionLeftInset), y: 0), animated: animated)
}
Sample gif
Set conentInset value to your collectionView like this:
myCollectionView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
and then add this line:
if #available(iOS 11, *) {
self.myCollectionView.contentInsetAdjustmentBehavior = .never
}
then scrolltoItem
works by respecting the insets of collectionView.
Since each cell's frame takes into account its section inset, you may as well use scrollRectToVisible(_:animated:).
let cell = collectionView.cellForItem(at: indexPath)!
collectionView.scrollRectToVisible(cell.frame, animated: true)
And since it is a frame we're working on, you can fine tune some desired offset to that frame.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With