PagingEnableLayout.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface PagingEnableLayout : UICollectionViewFlowLayout
+ (CGFloat)itemWidth ;
+ (CGFloat)collectionViewWidth ;
@end
NS_ASSUME_NONNULL_END
PagingEnableLayout.m
#import "PagingEnableLayout.h"
#import <objc/message.h>
@implementation PagingEnableLayout
+ (CGFloat)itemWidth {
return PagingEnableLayout.collectionViewWidth * 0.8;
}
+ (CGFloat)collectionViewWidth {
return [[UIScreen mainScreen] bounds].size.width;
}
- (void)prepareLayout{
[super prepareLayout];
CGFloat contentInset = PagingEnableLayout.collectionViewWidth - PagingEnableLayout.itemWidth;
self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast;
if ([self.collectionView respondsToSelector:NSSelectorFromString(@"_setInterpageSpacing:")]) {
((void(*)(id,SEL,CGSize))objc_msgSend)(self.collectionView, NSSelectorFromString(@"_setInterpageSpacing:"), CGSizeMake(-(contentInset-self.minimumLineSpacing), 0));
}
if ([self.collectionView respondsToSelector:NSSelectorFromString(@"_setPagingOrigin:")]) {
((void(*)(id,SEL,CGPoint))objc_msgSend)(self.collectionView, NSSelectorFromString(@"_setPagingOrigin:"), CGPointMake(0, 0));
}
}
@end
改变 CGSizeMake(-(contentInset-self.minimumLineSpacing), 0)
或 CGPointMake(0, 0)
中的 x
属性改变偏移量实现更多效果。
#import "ViewController.h"
#import "PagingEnableLayout.h"
@interface ViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *collectionView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.collectionView];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 5;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ID" forIndexPath:indexPath];
cell.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
return cell;
}
- (UICollectionView *)collectionView {
if (!_collectionView) {
PagingEnableLayout *layout = [[PagingEnableLayout alloc] init];
layout.itemSize = CGSizeMake(PagingEnableLayout.itemWidth, 500);
layout.minimumLineSpacing = 10;
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 200, PagingEnableLayout.collectionViewWidth, 500) collectionViewLayout:layout];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"ID"];
_collectionView.delegate = self;
_collectionView.dataSource = self;
_collectionView.backgroundColor = [UIColor whiteColor];
_collectionView.showsHorizontalScrollIndicator = NO;
_collectionView.pagingEnabled = YES;
}
return _collectionView;
}
@end
实现效果:
111.gif