Skip to content

Instantly share code, notes, and snippets.

@chrisbrandow
Created October 2, 2015 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisbrandow/4b35744ac67fc6976033 to your computer and use it in GitHub Desktop.
Save chrisbrandow/4b35744ac67fc6976033 to your computer and use it in GitHub Desktop.
An implementation of twitter suggested app side-swiping
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
targetContentOffset->x = [self targetOffsetX:targetContentOffset->x inCollectionView:(UICollectionView *)scrollView velocity:velocity];
}
- (CGFloat)targetOffsetX:(CGFloat)offsetX inCollectionView:(UICollectionView *)collectionView velocity:(CGPoint)velocity {
if (![collectionView isKindOfClass:[UICollectionView class]]) {
return offsetX;
}
NSInteger index = [self indexForScrollView:collectionView targetOffsetX:offsetX velocity:velocity];
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
return (index == 0) ? 0 : cell.frame.origin.x - (collectionView.frame.size.width - cell.frame.size.width)/2 ;
}
#define kDragVelocityDampener .85
- (NSInteger)indexForScrollView:(UICollectionView *)collectionView targetOffsetX:(CGFloat)offsetX velocity:(CGPoint)velocity {
NSInteger returnIndex = [self indexOfOffset:offsetX collectionView:collectionView velocity:velocity];
CGFloat originOfPan =[collectionView.panGestureRecognizer translationInView:self.view].x + collectionView.contentOffset.x;
NSInteger origIndex = [self indexOfOffset:originOfPan collectionView:collectionView velocity:velocity];
//Note: as the width of the cell gets much smaller than the width of the collection view, this becomes jerky.
if (labs(returnIndex - origIndex)> 1) {
return origIndex + ((velocity.x > 0) ? 1 : - 1);
}
return returnIndex;
}
- (NSInteger)indexOfOffset:(CGFloat)xOffset collectionView:(UICollectionView *)collectionView velocity:(CGPoint)velocity {
if (xOffset == 0) {
return 0;
} else {
CGFloat changeX = fabs(xOffset - collectionView.contentOffset.x)*kDragVelocityDampener;;
CGFloat width = [[collectionView visibleCells].firstObject frame].size.width;
return (velocity.x >= 0.f) ? ceil((xOffset - changeX)/width) : floor((xOffset + changeX)/width);
}
}
@chrisbrandow
Copy link
Author

No external state needed. one card swiped at a time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment