IOS实现自定义布局瀑布流

瀑布流是电商应用展示商品通常采用的一种方式,如图示例

瀑布流的实现方式,通常有以下几种

  • 通过UITableView实现(不常用)
  • 通过UIScrollView实现(工作量较大)
  • 通过UICollectionView实现(通常采用的方式)

一、UICollectionView基础
1、UICollectionView与UITableView有很多相似的地方,如

  • 都通过数据源提供数据
  • 都通过代理执行相关的事件
  • 都可以自定义cell,且涉及到cell的重用
  • 都继承自UIScrollView,具有滚动效果

2、UICollectionView的特性

  • 需要有一个UICollectionViewLayout类(通常是UICollectionViewFlowLayout类)或其子类对象,来决定cell的布局
  • 可以实现UICollectionViewLayout的子类,来定制UICollectionView的滚动方向以及cell的布局

3、UICollectionViewLayout的子类UICollectionViewFlowLayout

  • UICollectionViewFlowLayout即流水布局
  • 流水布局UICollectionView的最常用的一种布局方式

二、自定义布局
1、自定义布局需要实现UICollectionViewLayout的子类
2、自定义布局常用方法
初始化布局

- (void)prepareLayout
{
  //通常在该方法中完成布局的初始化操作
}

当尺寸改变时,是否更新布局

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
  //默认返回YES
}

布局UICollectionView的元素

- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
  //该方法需要返回rect区域中所有元素布局属性的数组
}
- (nullable UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
  //该方法返回indexPath位置的元素的布局属性
}

修改UICollectionView停止滚动是的偏移量

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
  //返回值是,UICollectionView最终停留的点
}

三、示例
1、实现效果

2、实现思路

  • 通过UICollectionView实现
  • 自定义布局,即横向流水布局和圆形普通布局
  • 通过UICollectionView的代理方法,当点击cell时,将其删除
  • 通过监听UIView的触摸事件,当点解控制器的view时更改布局

3、实现步骤
自定横向流水布局
初始化布局

- (void)prepareLayout
{
  [super prepareLayout];
  //设置滚动方向
  self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
  //设置内边距
  CGFloat inset = (self.collectionView.frame.size.width - self.itemSize.width) * 0.5;
  self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset);
}

指定当尺寸改变时,更新布局

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
  return YES;
}

设置所有元素的布局属性

- (nullable NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
  //获取rect区域中所有元素的布局属性
  NSArray *array = [super layoutAttributesForElementsInRect:rect];

  //获取UICollectionView的中点,以contentView的左上角为原点
  CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;

  //重置rect区域中所有元素的布局属性,即基于他们距离UICollectionView的中点的剧烈,改变其大小
  for (UICollectionViewLayoutAttributes *attribute in array)
  {
    //获取距离中点的距离
    CGFloat delta = ABS(attribute.center.x - centerX);
    //计算缩放比例
    CGFloat scale = 1 - delta / self.collectionView.bounds.size.width;
    //设置布局属性
    attribute.transform = CGAffineTransformMakeScale(scale, scale);
  }

  //返回所有元素的布局属性
  return [array copy];
}

设置UICollectionView停止滚动是的偏移量,使其为与中心点

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
  //计算最终显示的矩形框
  CGRect rect;
  rect.origin.x = proposedContentOffset.x;
  rect.origin.y = 0;
  rect.size = self.collectionView.frame.size;

  //获取最终显示在矩形框中的元素的布局属性
  NSArray *array = [super layoutAttributesForElementsInRect:rect];

  //获取UICollectionView的中点,以contentView的左上角为原点
  CGFloat centerX = proposedContentOffset.x + self.collectionView.frame.size.width * 0.5;

  //获取所有元素到中点的最短距离
  CGFloat minDelta = MAXFLOAT;
  for (UICollectionViewLayoutAttributes *attribute in array)
  {
    CGFloat delta = attribute.center.x - centerX;
    if (ABS(minDelta) > ABS(delta))
    {
      minDelta = delta;
    }
  }

  //改变UICollectionView的偏移量
  proposedContentOffset.x += minDelta;
  return proposedContentOffset;
}

自定义圆形普通布局
定义成员属性,保存所有的布局属性

@property (nonatomic, strong) NSMutableArray *attrsArray;

懒加载,初始化attrsArray

- (NSMutableArray *)attrsArray
{
  if (_attrsArray == nil)
  {
    _attrsArray = [NSMutableArray array];
  }
  return _attrsArray;
}

初始化布局

- (void)prepareLayout
{
  [super prepareLayout];

  //移除所有旧的布局属性
  [self.attrsArray removeAllObjects];

  //获取元素的个数
  NSInteger count = [self.collectionView numberOfItemsInSection:0];
  //布局所有的元素
  for (NSInteger i = 0; i<count; i++)
  {
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
    //设置并获取indexPath位置元素的布局属性
    UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
    //将indexPath位置元素的布局属性添加到所有布局属性数组中
    [self.attrsArray addObject:attrs];
  }
}

布局indexPath位置的元素

- (nullable UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
  //获取元素的个数
  NSInteger count = [self.collectionView numberOfItemsInSection:0];

  /**设置圆心布局*/
  //设置圆形的半径
  CGFloat radius = 70;
  //圆心的位置
  CGFloat oX = self.collectionView.frame.size.width * 0.5;
  CGFloat oY = self.collectionView.frame.size.height * 0.5;
  //获取indexPath位置的元素的布局属性
  UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
  //设置尺寸
  attrs.size = CGSizeMake(50, 50);
  //设置位置
  if (count == 1)
  {
    attrs.center = CGPointMake(oX, oY);
  }
  else
  {
    CGFloat angle = (2 * M_PI / count) * indexPath.item;
    CGFloat centerX = oX + radius * sin(angle);
    CGFloat centerY = oY + radius * cos(angle);
    attrs.center = CGPointMake(centerX, centerY);
  }
  //返回indexPath位置元素的布局属性
  return attrs;
}

布局指定区域内所有的元素

- (nullable NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
  //返回所有元素的布局属性
  return self.attrsArray;
}

通过xib自定义ce ll
设置成员属性,保存cell内部的图片

/**图片名字*/

@property (nonatomic, copy) NSString *imageName;

初始化cell

- (void)awakeFromNib
{
  //通过Layer设置边框
  self.imageView.layer.borderColor = [UIColor whiteColor].CGColor;
  self.imageView.layer.borderWidth = 6;
  self.imageView.layer.cornerRadius = 3;
}

设置cell内imageView的image属性

- (void)setImageName:(NSString *)imageName
{
  _imageName = [imageName copy];
  self.imageView.image = [UIImage imageNamed:imageName];
}

加载图片资源
通过成员属性,保存所有的图片名

/**所有的图片*/
@property (nonatomic, strong) NSMutableArray *imageNames;

懒加载,初始化图片名数组

- (NSMutableArray *)imageNames
{
  if (_imageNames == nil)
  {
    NSMutableArray *imageNames = [NSMutableArray array];
    for (NSInteger i = 0; i<20; i++)
    {
      NSString *imageName = [NSString stringWithFormat:@"%zd", i + 1];
      [imageNames addObject:imageName];
    }
    _imageNames = imageNames;
  }
  return _imageNames;
}

创建UICollectionView
通过成员属性保存UICollectionView对象,以便更改布局

@property (nonatomic, weak) UICollectionView *collectionView;

创建并设置collectionView

- (void)setupCollectionView
{
  //设置frame
  CGFloat collectionViewW = self.view.bounds.size.width;
  CGFloat collectionViewH = 200;
  CGRect frame = CGRectMake(0, 150, collectionViewW, collectionViewH);

  //创建布局
  LYPCircleLayout *layout = [[LYPCircleLayout alloc] init];

  //创建collectionView
  UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
  self.collectionView = collectionView;

  //设置collectionView的数据源和代理
  collectionView.dataSource = self;
  collectionView.delegate = self;

  //添加collectionView到控制器的view中
  [self.view addSubview:collectionView];
}

实现UICollectionView的数据源方法
注册cell

/**设置重用表示*/
static NSString *const ID = @"photo";
- (void)viewDidLoad
{
  [super viewDidLoad];

  [self setupCollectionView];

  //注册cell
  [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([LYPPhotoCell class]) bundle:nil] forCellWithReuseIdentifier:ID];
}

设置元素的个数

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

设置每个元素的属性

- (UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
  //根据重用标示从缓存池中取出cell,若缓存池中没有,则自动创建
  LYPPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
  //设置cell的imageName属性
  cell.imageName = self.imageNames[indexPath.item];

  //返回cell
  return cell;
}

实现UICollectionView的代理方法,实现点击某个元素将其删除功能

- (void)collectionView:(nonnull UICollectionView *)collectionView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
  //将图片名从数组中移除
  [self.imageNames removeObjectAtIndex:indexPath.item];
  //删除collectionView中的indexPath位置的元素
  [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
}

监听控制器view的点击,更换布局

- (void)touchesBegan:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
{
  //判断当前布局的种类
  if ([self.collectionView.collectionViewLayout isKindOfClass:[LYPLineLayout class]])
  {
    //流水布局,切换至圆形布局
    [self.collectionView setCollectionViewLayout:[[LYPCircleLayout alloc] init] animated:YES];
  } else
  {
    //圆形布局,切换至流水布局
    LYPLineLayout *layout = [[LYPLineLayout alloc] init];
    //设置元素的尺寸,若不设置,将使用自动计算尺寸
    layout.itemSize = CGSizeMake(130, 130);
    [self.collectionView setCollectionViewLayout:layout animated:YES];
  }
}

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

(0)

相关推荐

  • 三种方式实现瀑布流布局

    分别使用javascript,jquery,css实现瀑布流布局: 第一种方式:使用JavaScript: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>瀑布流布局</title> <style> *{padding:0;margin:0;} .clearfix:after, .clearf

  • 解析瀑布流布局:JS+绝对定位的实现

    绝对定位方式的瀑布流布局: 一.布局 1.包围块框的容器: 复制代码 代码如下: <div id="main">    ... ...<div> 2.一个块框: 复制代码 代码如下: <div class="pin">    <div class="box">        <img src="./images/g (1).jpg"/>    </div>

  • 原生JS实现响应式瀑布流布局

    原生JS实现的瀑布流布局,代码及demo代码地址:https://github.com/leozdgao/responsive_waterfall Demo:http://leozdgao.github.io/demo/responsive_waterfall/ 演示图: 核心代码: responsive_waterfall.js (function() { var Waterfall = function(opts) { var minBoxWidth; Object.defineProper

  • 网页瀑布流布局jQuery实现代码

    什么是瀑布流网页布局? 瀑布流,又称瀑布流式布局.是比较流行的一种网站页面布局,视觉表现为参差不齐的多栏布局,随着页面滚动条向下滚动,这种布局还会不断加载数据块并附加至当前尾部. 下面来看代码,用纯CSS3来做看效果怎样! HTML <div id="all"> <div class="box"> <div class="pic"> <img src="cars/1.jpg"/>

  • AJAX实现瀑布流布局

    瀑布流是当前一种比较流行的网站界面布局方式,参差不齐的多栏布局以及到达底部自动加载的方式,使网站在视觉和用户体验上都能得到较大的提升.最早使用此布局的是国外的图片网站Pinterest,之后国内的一些图片网站也开始使用瀑布流布局,包括和Pinterest类似的花瓣网.图片社区lofter.美丽说.蘑菇街等等. 瀑布流在布局上对于大多数人来说应该是很简单的,比较只有几列而已.瀑布流最主要的还是数据的异步加载. 首先说一下这次实例所用的瀑布流式方法.瀑布流布局实现的方法很多,具体可以自行百度,此处不

  • jQuery实现瀑布流布局

    HTML 复制代码 代码如下: <div id="main">          <div class="box">              <div class="pic">                  <img src="images/0.jpg" alt="">              </div>          </di

  • jquery实现简单的瀑布流布局

    是开头都会说的原理 瀑布流布局有两种,一种是固定列,一种是非固定列.在此主要记述第一种的实现. 固定列的特征是:无论页面如何缩放,每行的总列数都一致. 一行4列的瀑布流从布局的角度来说,就是4个li标签.通过一定的事件(比如滚动条滚动多少px),然后读取之,再把数据动态地添加到页面中. 添加数据原则,不是根据li索引值来加,而是根据各列中高度最短的的那列动态添加.否则可能导致页面很难看(左右高度不统一). 实例涉及ajax方法.可在服务器环境下运行. 废话不多说了.直接上样式. <ul id=&qu

  • 纯js实现瀑布流布局及ajax动态新增数据

    本文用纯js代码手写一个瀑布流网页效果,初步实现一个基本的瀑布流布局,以及滚动到底部后模拟ajax数据加载新图片功能. 缺点: 1. 程序不是响应式,不能实时调整页面宽度: 2. 程序中当新增ajax模拟数据图片后,是将整个页面的所有图片都重新定位一次. 3. 程序是等所有图片加载完成后再读取图片的尺寸,实际中肯定不能这样做. 4. 实际项目中,应该由后台程序给出图片尺寸值,在js代码中直接使用图片的width属性. 本程序思路: html结构: <body> <div id="

  • jQuery实现瀑布流布局详解(PC和移动端)

    瀑布流布局已成为当今非常普遍的图片展示方式,无论是PC还是手机等移动设备上.这种布局图片的样式大概分为三种:等高等宽.等宽不等高.等高不等宽,接下来我们就最为普遍的等宽不等高形式来作为示例. 我们用百度图片作为范例: 这就是PC端比较常见的瀑布流布局方式,接下来我们审查下元素看看百度图片里面是如何布局: 可以看到,它里面实际是若干个等宽的列容器,通过计算将图片push到不同的容器里.而本文介绍的展示方法是通过定位的方式,虽然最后布局展示的方式不同,但之前的算法都比较类似. 动手 首先我们将如下样

  • jQuery+HTML5美女瀑布流布局实现方法

    本文实例讲述了jQuery+HTML5美女瀑布流布局实现方法.分享给大家供大家参考.具体如下: 这是一款JavaScript与HTML5实现美女瀑布流布局,本方法是把图片的路径写在了JS的数组里,不过重点好像不是在这里,而是在图片如何自动排列的问题,你可以运行本实例后,点击"加载瀑布流布局"按钮,即可看到图片的瀑布流排列效果,现在很流行这个,希望您从本代码中能找到一些灵感. 运行效果截图如下: 在线演示地址如下: http://demo.jb51.net/js/2015/js-html

随机推荐