Adjust collectionView.scrollToItem to consider inset?
You can use the regular method collectionView.scrollToItem
if you set your inset in collectionView.contentInset
instead of layout.sectionInset
.
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.
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