原文章地址:http://blog.csdn.net/a_ss_a/article/details/47785013
#pragma mark -- 主要实现在于自定义UICollectionViewFlowLayout
#import <UIKit/UIKit.h>
@protocol CustomViewFlowLayoutDelegate <UICollectionViewDelegateFlowLayout>
- (void)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout cellCenteredAtIndexPath:(NSIndexPath *)indexPath page:(int)page;
@end
@interface SSGiftCollectionViewFlowLayout : UICollectionViewFlowLayout
@property (nonatomic, weak) id<CustomViewFlowLayoutDelegate> delegate;
@end
@implementation SSGiftCollectionViewFlowLayout
- (void)prepareLayout{
[super prepareLayout];
}
- (id)init {
if (self = [super init]) {
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.minimumInteritemSpacing = 0.0f;
self.sectionInset = UIEdgeInsetsZero;
self.itemSize = CGSizeMake(100.f ,100.f);
self.minimumLineSpacing = 0;
}
return self;
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return YES;
}
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
CGRect visibleRect;
visibleRect.origin = self.collectionView.contentOffset;
visibleRect.size = self.collectionView.bounds.size;
for (UICollectionViewLayoutAttributes *attribute in attributes) {
if (CGRectIntersectsRect(attribute.frame, rect)) {
if (visibleRect.origin.x == 0) {
[self.delegate collectionView:self.collectionView layout:self cellCenteredAtIndexPath:attribute.indexPath page:0];
}else{
// 除法取整 取余数
div_t x = div(visibleRect.origin.x,visibleRect.size.width);
if (x.quot > 0 && x.rem > 0) {
[self.delegate collectionView:self.collectionView layout:self cellCenteredAtIndexPath:attribute.indexPath page:x.quot + 1];
}
if (x.quot > 0 && x.rem == 0) {
[self.delegate collectionView:self.collectionView layout:self cellCenteredAtIndexPath:attribute.indexPath page:x.quot];
}
}
}
}
return attributes;
}
- (UICollectionView *)aCollectionView{
if (_aCollectionView != nil) {
return _aCollectionView;
}
SSGiftCollectionViewFlowLayout *viewFlowLayout = [[SSGiftCollectionViewFlowLayout alloc] init];
viewFlowLayout.delegate = self;
_aCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:viewFlowLayout];
_aCollectionView.showsHorizontalScrollIndicator = FALSE; // 去掉滚动条
_aCollectionView.alwaysBounceHorizontal = YES;
_aCollectionView.pagingEnabled = YES;
_aCollectionView.scrollEnabled = YES;
_aCollectionView.delegate = self;
_aCollectionView.dataSource = self;
[_aCollectionView registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:identifier];
return _aCollectionView;
}
- (void)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout cellCenteredAtIndexPath:(NSIndexPath *)indexPath page:(int)page{
self.pageControl.currentPage = page; // 分页控制器当前显示的页数
}