preface
I am doing a travel project recently, which has the horizontal sliding TAB function. At first glance, I feel very simple. Scroll horizontally. The flowLayout of the CollectionView has this property. Later, you need to slide one TAB at a time. And that makes it a little tricky for me, because I know that this is supposed to be a problem of calculating the offset myself
To the chase
To do this, Main agents is to call a UIScrollView method – (void) scrollViewWillEndDragging: (UIScrollView *) scrollView withVelocity (CGPoint) velocity targetContentOffset:(inout CGPoint *)targetContentOffset
So without saying anything else, just go to the code
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
float pageWidth = 200 + 10;
float currentOffset = _collectionView.contentOffset.x;
float targetOffset = targetContentOffset->x;
float newTargetOffset = 0;
if (targetOffset+ 20 > currentOffset) {
newTargetOffset = ceilf(currentOffset/pageWidth) * pageWidth;
}else{
newTargetOffset = floorf(currentOffset/ pageWidth) * pageWidth;
}
if (newTargetOffset < 0) {
newTargetOffset = 0;
}else if (ABS(scrollView.contentSize.width - (newTargetOffset + pageWidth))< pageWidth){
newTargetOffset = scrollView.contentSize.width - _collectionView.bounds.size.width ;
}
newTargetOffset = ceilf(newTargetOffset);
targetContentOffset->x = currentOffset;
[scrollView setContentOffset:CGPointMake(newTargetOffset, 0) animated:YES];
}
Copy the code
The value of pageWidth is the width of an item plus the spacing, and then the width of less than one item is handled accordingly when the last item is slid.
If your design has white space on both sides, you can set flowLayout.sectionInset and the corresponding collectionView’s contentInset property
OS:
Do the gods have any good suggestions for me
portal
Demo