JFLoopViewCell.h文件
#import <UIKit/UIKit.h>
@interface JFLoopViewCell : UICollectionViewCell
@property (nonatomic, copy) NSString *imageName;
@end
JFLoopViewCell.m文件
#import "JFLoopViewCell.h"
@interface JFLoopViewCell ()
@property (nonatomic, weak) UIImageView *iconView;
@end
@implementation JFLoopViewCell
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
UIImageView *iconView = [[UIImageView alloc] init];
[self addSubview:iconView];
self.iconView = iconView;
}
return self;
}
- (void)setImageName:(NSString *)imageName {
_imageName = imageName;
self.iconView.image = [UIImage imageNamed:imageName];
}
- (void)layoutSubviews {
[super layoutSubviews];
self.iconView.frame = self.bounds;
}
@end
JFLoopViewLayout.h文件
#import <UIKit/UIKit.h>
@interface JFLoopViewLayout : UICollectionViewFlowLayout
@end
JFLoopViewLayout.m文件
#import "JFLoopViewLayout.h"
@implementation JFLoopViewLayout
/// 准备布局
- (void)prepareLayout {
[super prepareLayout];
//设置item尺寸
self.itemSize = self.collectionView.frame.size;
//设置滚动方向
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//设置分页
self.collectionView.pagingEnabled = YES;
//设置最小间距
self.minimumLineSpacing = 0;
self.minimumInteritemSpacing = 0;
//隐藏水平滚动条
self.collectionView.showsHorizontalScrollIndicator = NO;
}
@end
JFMainViewController.h文件
#import <UIKit/UIKit.h>
@interface JFMainViewController : UIViewController
@end
JFMainViewController.m文件
#import "JFMainViewController.h"
#import "JFLoopView.h"
@interface JFMainViewController ()
@property (nonatomic, strong) JFLoopView *loopView;
@end
@implementation JFMainViewController
- (void)viewDidLoad {
[super viewDidLoad];
//关闭自动调整滚动视图
self.automaticallyAdjustsScrollViewInsets = NO;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.navigationController.navigationBar.hidden = YES;
}
- (void)loadView {
[super loadView];
//设置图片数据
NSArray *imageArray = @[@"srcoll_01",@"srcoll_02",@"srcoll_03"];
//此行代码实现无限轮播
_loopView = [[JFLoopView alloc] initWithImageArray:imageArray];
//设置loopView的frame
_loopView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 250);
[self.view addSubview:self.loopView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
注意:如果你的控制器有UINavigationBar,且隐藏了navigationBar,一定要记得设置self.automaticallyAdjustsScrollViewInsets = NO; automaticallyAdjustsScrollViewInsets是干嘛的呢?简单点说就是automaticallyAdjustsScrollViewInsets根据所在界面的status bar、navigationbar、与tabbar的高度,自动调整scrollview的 inset,设置为NO,不让viewController调整,我们自己修改布局即可。如果不设置为NO就可能出现下面的情况,自动滚动和拖动的时候imageView的位置会变化。










