iOS开发实战 - 实现scrollView和collectio
2018-05-03 本文已影响118人
ArchLL
系统自带的Paging Enabled会把scrollView/collectionView的contentSize平均分割成几部分,每页滑动的距离不能自己控制,如下面的演示图片,每页滑动的距离是 cell.width + space + 下一个cell的一小部分,这里将介绍如何自定义每页滑动的距离,并优雅的运用到自己的项目中

部分代码:
#define itemWidth self.width-20-34
#define itemHeight self.height-20
@implementation XXHomeBrandCell
{
NSInteger selectedIndex;
}
- (void)awakeFromNib {
[super awakeFromNib];
[_collectionView registerNib:[UINib nibWithNibName:@"XXHomeBrandItem" bundle:nil] forCellWithReuseIdentifier:@"XXHomeBrandItem"];
selectedIndex = 0;
}
//主要代码
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
CGFloat x = targetContentOffset->x;
CGFloat pageWidth = itemWidth + 20;
CGFloat movedX = x - pageWidth * selectedIndex;
if (movedX < -pageWidth * 0.5) {
// Move left
selectedIndex--;
} else if (movedX > pageWidth * 0.5) {
// Move right
selectedIndex++;
}
if (ABS(velocity.x) >= 2){
targetContentOffset->x = pageWidth * selectedIndex;
} else {
targetContentOffset->x = scrollView.contentOffset.x;
[scrollView setContentOffset:CGPointMake(pageWidth * selectedIndex, scrollView.contentOffset.y) animated:YES];
}
NSLog(@"%ld",selectedIndex);
}
#pragma mark FlowLayoutDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(itemWidth, self.height-20);
}




参考:
https://github.com/Silence-GitHub/PageScrollViewDemo/blob/master/PageScrollViewDemo/PageScrollVC.swift
里面包含scrollView和collectionView的自定义分页,不过都是swift版本