ios uicollectionview实现横向滚动

现在使用卡片效果的app很多,之前公司让实现一种卡片效果,就写了一篇关于实现卡片的文章。文章最后附有demo
实现上我选择了使用UICollectionView ;用UICollectionViewFlowLayout来定制样式;下面看看具体实现

效果

实现上我选择了使用UICollectionView ;用UICollectionViewFlowLayout来定制样式;下面看看具体实现

具体实现

1、ViViewController.m 代码实现

#import "ViewController.h"
#import "CollModel.h"
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SCREEN_RATE ([UIScreen mainScreen].bounds.size.width/375.0)
#import "imageCell.h"
#import "LHHorizontalPageFlowlayout.h"
static NSString * const imageC = @"imageCell";
static NSString * const moreImageC = @"imageCell";
static const NSInteger kItemCountPerRow = 5; //每行显示5个
static const NSInteger kRowCount = 3; //每页显示行数
static float imageHeight = 80;//cell 高度
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, strong) NSMutableArray * modelArray;
@property (nonatomic, strong) UICollectionView * moreCollectionView;
@end
@implementation ViewController
- (void)viewDidLoad {
 [super viewDidLoad];
 NSArray *appArray = [[self getDict] objectForKey:@"dictInfo"];
 for (int i = 0; i < appArray.count; i++) {
  NSDictionary * appDic = appArray[i];
  CollModel * model = [[CollModel alloc]init];
  model.title = [appDic objectForKey:@"title"];
  model.url = [appDic objectForKey:@"url"];
  [self.modelArray addObject:model];
 }
 [self createCollectionView];
 [self createRightCollectionView];
}

- (NSDictionary *)getDict {
 NSString * string = @"{\"dictInfo\":[{\"title\":\"你好啊\",\"url\":\"1.jpeg\"},{\"title\":\"你好啊\",\"url\":\"2.jpeg\"},{\"title\":\"你好啊\",\"url\":\"3.jpeg\"},{\"title\":\"你好啊\",\"url\":\"4.jpeg\"},{\"title\":\"你好啊\",\"url\":\"5.jpeg\"},{\"title\":\"你好啊\",\"url\":\"6.jpeg\"},{\"title\":\"是很好\",\"url\":\"7.jpeg\"},{\"title\":\"你好啊\",\"url\":\"1.jpeg\"},{\"title\":\"你好啊\",\"url\":\"2.jpeg\"},{\"title\":\"你好啊\",\"url\":\"3.jpeg\"},{\"title\":\"你好啊\",\"url\":\"4.jpeg\"},{\"title\":\"你好啊\",\"url\":\"5.jpeg\"},{\"title\":\"你好啊\",\"url\":\"6.jpeg\"},{\"title\":\"是很好\",\"url\":\"7.jpeg\"},{\"title\":\"你好啊\",\"url\":\"1.jpeg\"},{\"title\":\"你好啊\",\"url\":\"2.jpeg\"},{\"title\":\"你好啊\",\"url\":\"3.jpeg\"},{\"title\":\"你好啊\",\"url\":\"4.jpeg\"},{\"title\":\"你好啊\",\"url\":\"5.jpeg\"},{\"title\":\"你好啊\",\"url\":\"6.jpeg\"},{\"title\":\"是很好\",\"url\":\"7.jpeg\"}]}";
 NSDictionary *infoDic = [self dictionaryWithJsonString:string];
 return infoDic;
}

-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
 if (jsonString == nil) {
  return nil;
 }
 NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
 NSError *err;
 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
 if(err)
 {
  NSLog(@"json解析失败:%@",err);
  return nil;
 }
 return dic;
}

- (NSMutableArray *)modelArray {
 if (!_modelArray) {
  _modelArray = [NSMutableArray array];
 }
 return _modelArray;
}

- (void)createCollectionView{
 UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
 layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
 layout.minimumLineSpacing = 0;
 layout.minimumInteritemSpacing = 0;
 _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, imageHeight * SCREEN_RATE) collectionViewLayout:layout];
 _collectionView.tag = 11;
 _collectionView.backgroundColor = [UIColor colorWithRed:186 / 255.0 green:186 / 255.0 blue:186 / 255.0 alpha:0.9];
 _collectionView.dataSource = self;
 _collectionView.delegate = self;
 _collectionView.bounces = NO;
 _collectionView.alwaysBounceHorizontal = YES;
 _collectionView.alwaysBounceVertical = NO;
 _collectionView.showsHorizontalScrollIndicator = NO;
 _collectionView.showsVerticalScrollIndicator = NO;
 [self.view addSubview:_collectionView];
 [_collectionView registerClass:[imageCell class] forCellWithReuseIdentifier:imageC];
}

- (void)createRightCollectionView{

 LHHorizontalPageFlowlayout * layout = [[LHHorizontalPageFlowlayout alloc] initWithRowCount:kRowCount itemCountPerRow:kItemCountPerRow];
 [layout setColumnSpacing:0 rowSpacing:0 edgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
 layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
 // UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
 // layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
 layout.minimumLineSpacing = 0;
 layout.minimumInteritemSpacing = 0;
 _moreCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 300, [UIScreen mainScreen].bounds.size.width, imageHeight * SCREEN_RATE * kRowCount) collectionViewLayout:layout];
 _moreCollectionView.backgroundColor = [UIColor clearColor];
 _moreCollectionView.tag = 22;
 _moreCollectionView.dataSource = self;
 _moreCollectionView.delegate = self;
 _moreCollectionView.bounces = NO;
 _moreCollectionView.alwaysBounceHorizontal = YES;
 _moreCollectionView.alwaysBounceVertical = NO;
 _moreCollectionView.backgroundColor = [UIColor colorWithRed:186 / 255.0 green:186 / 255.0 blue:186 / 255.0 alpha:0.9];
 _moreCollectionView.showsHorizontalScrollIndicator = NO;
 _moreCollectionView.showsVerticalScrollIndicator = NO;
 [self.view addSubview:_moreCollectionView];
 [_moreCollectionView registerClass:[imageCell class] forCellWithReuseIdentifier:moreImageC];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
 return self.modelArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
 CollModel * model = self.modelArray[indexPath.row];
 imageCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:imageC forIndexPath:indexPath];
 cell.itemModel = model;
 return cell;
}

// 返回每个item的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
 CGFloat CWidth = imageHeight * SCREEN_RATE;
 CGFloat CHeight = imageHeight * SCREEN_RATE;
 return CGSizeMake(CWidth, CHeight);
}

#pragma mark - UICollectionViewDelegate点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
 CollModel * model = self.modelArray[indexPath.row];
 NSLog(@"self.appModelArray----%@",model.title);
}

- (void)didReceiveMemoryWarning {
 [super didReceiveMemoryWarning];
 // Dispose of any resources that can be recreated.
}

@end

2、自定义UICollectionViewFlowLayout

LHHorizontalPageFlowlayout.h 实现

#import <UIKit/UIKit.h>
@interface LHHorizontalPageFlowlayout : UICollectionViewFlowLayout
/** 列间距 */
@property (nonatomic, assign) CGFloat columnSpacing;
/** 行间距 */
@property (nonatomic, assign) CGFloat rowSpacing;
/** collectionView的内边距 */
@property (nonatomic, assign) UIEdgeInsets edgeInsets;

/** 多少行 */
@property (nonatomic, assign) NSInteger rowCount;
/** 每行展示多少个item */
@property (nonatomic, assign) NSInteger itemCountPerRow;

//固定宽度
@property (nonatomic, assign) CGFloat itemWidth; //设置完这个,就会自动计算列间距
//固定高度
@property (nonatomic, assign) CGFloat itemHight;//设置完这个,就会自动计算行间距

/** 所有item的属性数组 */
@property (nonatomic, strong) NSMutableArray *attributesArrayM;

/** 设置行列间距及collectionView的内边距 */
- (void)setColumnSpacing:(CGFloat)columnSpacing rowSpacing:(CGFloat)rowSpacing edgeInsets:(UIEdgeInsets)edgeInsets;
/** 设置多少行及每行展示的item个数 */
- (void)setRowCount:(NSInteger)rowCount itemCountPerRow:(NSInteger)itemCountPerRow;

#pragma mark - 构造方法
/** 设置多少行及每行展示的item个数 */
+ (instancetype)horizontalPageFlowlayoutWithRowCount:(NSInteger)rowCount itemCountPerRow:(NSInteger)itemCountPerRow;
/** 设置多少行及每行展示的item个数 */
- (instancetype)initWithRowCount:(NSInteger)rowCount itemCountPerRow:(NSInteger)itemCountPerRow;

@end

LHHorizontalPageFlowlayout.m 实现

#import "LHHorizontalPageFlowlayout.h"

@implementation LHHorizontalPageFlowlayout

#pragma mark - Public
- (void)setColumnSpacing:(CGFloat)columnSpacing rowSpacing:(CGFloat)rowSpacing edgeInsets:(UIEdgeInsets)edgeInsets
{
 self.columnSpacing = columnSpacing;
 self.rowSpacing = rowSpacing;
 self.edgeInsets = edgeInsets;
}

- (void)setRowCount:(NSInteger)rowCount itemCountPerRow:(NSInteger)itemCountPerRow
{
 self.rowCount = rowCount;
 self.itemCountPerRow = itemCountPerRow;
}

#pragma mark - 构造方法
+ (instancetype)horizontalPageFlowlayoutWithRowCount:(NSInteger)rowCount itemCountPerRow:(NSInteger)itemCountPerRow
{
 return [[self alloc] initWithRowCount:rowCount itemCountPerRow:itemCountPerRow];
}

- (instancetype)initWithRowCount:(NSInteger)rowCount itemCountPerRow:(NSInteger)itemCountPerRow
{
 self = [super init];
 if (self) {
  self.rowCount = rowCount;
  self.itemCountPerRow = itemCountPerRow;
 }
 return self;
}

#pragma mark - 重写父类方法
- (instancetype)init
{
 self = [super init];
 if (self) {
  [self setColumnSpacing:0 rowSpacing:0 edgeInsets:UIEdgeInsetsZero];
 }
 return self;
}

/** 布局前做一些准备工作 */
- (void)prepareLayout
{
 [super prepareLayout];
 if (self.attributesArrayM && self.attributesArrayM.count > 0) {
  [self.attributesArrayM removeAllObjects];
 }

 // 从collectionView中获取到有多少个item
 NSInteger itemTotalCount = [self.collectionView numberOfItemsInSection:0];

 // 遍历出item的attributes,把它添加到管理它的属性数组中去
 for (int i = 0; i < itemTotalCount; i++) {
  NSIndexPath *indexpath = [NSIndexPath indexPathForItem:i inSection:0];
  UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexpath];
  [self.attributesArrayM addObject:attributes];
 }
}

/** 计算collectionView的滚动范围 */
- (CGSize)collectionViewContentSize
{
 // 计算出item的宽度
 CGFloat itemWidth = (self.collectionView.frame.size.width - self.edgeInsets.left - self.itemCountPerRow * self.columnSpacing) / self.itemCountPerRow;
 // 从collectionView中获取到有多少个item
 NSInteger itemTotalCount = [self.collectionView numberOfItemsInSection:0];

 // 理论上每页展示的item数目
 NSInteger itemCount = self.rowCount * self.itemCountPerRow;
 // 余数(用于确定最后一页展示的item个数)
 NSInteger remainder = itemTotalCount % itemCount;
 // 除数(用于判断页数)
 NSInteger pageNumber = itemTotalCount / itemCount;
 // 总个数小于self.rowCount * self.itemCountPerRow
 if (itemTotalCount <= itemCount) {
  pageNumber = 1;
 }else {
  if (remainder == 0) {
   pageNumber = pageNumber;
  }else {
   // 余数不为0,除数加1
   pageNumber = pageNumber + 1;
  }
 }

 CGFloat width = 0;
 // 考虑特殊情况(当item的总个数不是self.rowCount * self.itemCountPerRow的整数倍,并且余数小于每行展示的个数的时候)
 if (pageNumber > 1 && remainder != 0 && remainder < self.itemCountPerRow) {
  width = self.edgeInsets.left + (pageNumber - 1) * self.itemCountPerRow * (itemWidth + self.columnSpacing) + remainder * itemWidth + (remainder - 1)*self.columnSpacing + self.edgeInsets.right;
 }else {
  width = self.edgeInsets.left + pageNumber * self.itemCountPerRow * (itemWidth + self.columnSpacing) - self.columnSpacing + self.edgeInsets.right;
 }

 // 只支持水平方向上的滚动
 return CGSizeMake(width, 150);
}

/** 设置每个item的属性(主要是frame) */
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
 // item的宽高由行列间距和collectionView的内边距决定
 CGFloat itemWidth = (self.collectionView.frame.size.width) / self.itemCountPerRow;
 CGFloat itemHeight = (self.collectionView.frame.size.height) / self.rowCount;

 NSInteger item = indexPath.item;
 // 当前item所在的页
 NSInteger pageNumber = item / (self.rowCount * self.itemCountPerRow);
 NSInteger x = item % self.itemCountPerRow + pageNumber * self.itemCountPerRow;
 NSInteger y = item / self.itemCountPerRow - pageNumber * self.rowCount;

 // 计算出item的坐标
 CGFloat itemX = itemWidth * x;
 CGFloat itemY = itemHeight * y;

 UICollectionViewLayoutAttributes *attributes = [super layoutAttributesForItemAtIndexPath:indexPath];
 // 每个item的frame
 attributes.frame = CGRectMake(itemX, itemY, itemWidth, itemHeight);

 return attributes;
}

/** 返回collectionView视图中所有视图的属性数组 */
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
 return self.attributesArrayM;
}

#pragma mark - Lazy
- (NSMutableArray *)attributesArrayM
{
 if (!_attributesArrayM) {
  _attributesArrayM = [NSMutableArray array];
 }
 return _attributesArrayM;
}
@end

4、自定义cell 和model

model

#import <Foundation/Foundation.h>

@interface CollModel : NSObject
@property (nonatomic,strong)NSString *imgUrl;
@property (nonatomic,strong)NSString *title;
@property (nonatomic,strong)NSString *url;
@end

cell 自定义

#import "imageCell.h"
// 屏幕比例
#define SCREEN_RATE  ([UIScreen mainScreen].bounds.size.width/375.0)

@interface imageCell()
@property (nonatomic, strong) UIImageView *itemIcon;
@end

@implementation imageCell

@synthesize itemModel = _itemModel;

- (instancetype)initWithFrame:(CGRect)frame{
 if (self = [super initWithFrame:frame]) {
  self.contentView.backgroundColor = [UIColor clearColor];
  [self initView];
 }
 return self;
}

- (void)initView{
 _itemIcon = [[UIImageView alloc] init];
 [self.contentView addSubview:_itemIcon];
 _itemIcon.backgroundColor = [UIColor clearColor];
 CGFloat iconWidth = 80 * SCREEN_RATE;
 _itemIcon.frame = CGRectMake(0, 0, iconWidth, iconWidth);
 _itemIcon.center = self.contentView.center;
}

- (CollModel *)itemModel{
 return _itemModel;
}

- (void)setItemModel:(CollModel *)itemModel
{
 if (!itemModel) {
  return;
 }
 _itemModel = itemModel;

 [self setCellWithModel:_itemModel];
}

- (void)setCellWithModel:(CollModel *)itemModel{
 [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  _itemIcon.image = [UIImage imageNamed:itemModel.url];
 }];
}

下载:ios uicollectionview横向滚动

GitHub下载

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

时间: 2020-03-22

iOS使用UICollectionView实现横向滚动照片效果

本文实例为大家分享了iOS使用UICollectionView实现横向滚动展示照片的具体代码,供大家参考,具体内容如下 这是Demo链接 效果图 思路 1. 界面搭建 界面的搭建十分简单,采用UICollectionView和自定义cell进行搭建即可. // ViewController.m // 下面使用到的宏和全局变量 #define ScreenW [UIScreen mainScreen].bounds.size.width #define ScreenH [UIScreen main

iOS Swift UICollectionView横向分页滚动,cell左右排版问题详解

情况 Swift对于一门新的iOS编程语言,他的崛起是必然的,我们这群老程序员们学习新的技能也是必然的,不接受新技能将被这大群体无情的淘汰. 最近因为工作的需求,在做表情键盘时遇到一个问题,我用UICollectionView来布局表情,使用横向分页滚动,但在最后一页出现了如图所示的情况 情况分析图 是的,现在的item分布就是这个鬼样子 现在想要做的,就是将现在这个鬼样子变成另外一种样子,如图 那怎么办?只好重新布局item了 解决方案 我是自定了一个Layout(LXFChatEmotion

iOS中关于Swift UICollectionView横向分页的问题

下面通过图文并茂的形式给大家介绍UICollectionView横向分页的问题,具体内容详情如下所示: 情况 直接看图 滚前 滚后 已经设置collectionView的isPagingEnabled为true了,可是出现了这种情况,原因就是collectionView的contentSize不够. <UICollectionView: 0x7fc565076000; frame = (0 0; 375 197); clipsToBounds = YES; gestureRecognizers

iOS开发中以application/json上传文件实例详解

本文通过实例代码给大家讲解iOS中以application/json上传文件的形式,具体内容详情大家参考下本文. 在和sever后台交互的过程中.有时候.他们需要我们iOS开发者以"application/json"形式上传. NSString *accessUrl = [NSString stringWithFormat:@"%@/xxx",@"https://www.xxxxx.com:xxxx"]; NSMutableURLRequest

IOS 简单的本地json格式文件解析的实例详解

IOS 简单的本地json格式文件解析的实例详解 ljweibo.json文件 { "data":[{ "name" : "孙悟空", "content" : "7月12日的国务院常务会议上,李克强明确要求,要将已审议的<快递条例(草案)>向社会公开征求意见.在会上,总理说了这么一段话:"几年前,快递业刚刚开始发展的时候,有些城市不允许快递存在,理由是影响市容整洁,快递员骑的摩的也不允许停放.但

iOS Webview自适应实际内容高度的4种方法详解

//第一种方法 - (void)webViewDidFinishLoad:(UIWebView *)webView { CGFloat webViewHeight=[webView.scrollView contentSize].height; CGRect newFrame = webView.frame; newFrame.size.height = webViewHeight; webView.frame = newFrame; _webTablewView.contentSize = C

Bootstrap分页插件之Bootstrap Paginator实例详解

Bootstrap Paginator是一款基于Bootstrap的js分页插件,功能很丰富,个人觉得这款插件已经无可挑剔了.它提供了一系列的参数用来支持用户的定制,提供了公共的方法可随时获得插件状态的改变,以及事件来监听用户的动作.目前经过测试的浏览器包括: Firefox 5+, Chrome 14+, Safari 5+, Opera 11.6+ and IE 7+. 官网地址:http://bootstrappaginator.org/ DownloadVisit Project in

jQuery Ajax自定义分页组件(jquery.loehpagerv1.0)实例详解

简单的两个步骤即可实现分页功能 <script src="<%=basePath%>/resources/js/jquery-1.7.1.min.js"></script> <script src="<%=basePath%>/resources/js/jquery.loehpagerv1.0.js"></script> <script type="text/JavaScript

iOS用AutoLayout实现分页滚动功能

滚动视图分页 UIScrollView的pagingEnabled属性用于控制是否按分页进行滚动.在一些应用中会应用到这一个特性,最典型的就是手机桌面的应用图标列表.这些界面中往往每一页功能都比较独立,系统也提供了UIPageViewController来实现这种分页滚动的功能. 实现分页滚动的UI实现一般是最外层一个UIScrollView.然后UIScrollView里面是一个总体的容器视图containerView.容器视图添加N个页视图,对于水平分页滚动来说容器视图的高度和滚动视图一样,

Swift流程控制之循环语句和判断语句详解

Swift提供了所有c类语言的控制流结构.包括for和while循环来执行一个任务多次:if和switch语句来执行确定的条件下不同的分支的代码:break和continue关键字能将运行流程转到你代码的另一个点上. 除了C语言传统的for-condition-increment循环,Swift加入了for-in循环,能更加容易的遍历arrays, dictionaries, ranges, strings等其他序列类型. Swift的switch语句也比C语言的要强大很多. Swift中swi

iOS开发教程之UIView和UIViewController的生命周期详解

前言 iOS开发中,创建View常见的两种方式一个是纯代码,一个是借助于XIB:创建ViewController常见的也有两种方式一个是纯代码,一个是借助于StoryBoard. 通过交流我发现很多童鞋对这些概念都很模糊,于是通过实验写一篇博客供参考. 重写View的如下方法 @implementation YFView -(instancetype)init{ self = [super init]; NSLog(@"%s", __func__); return self; } -(