UICollectionView——1.瀑布流(swift)

本文介绍了如何在Swift中利用UICollectionViewFlowLayout子类实现瀑布流布局。主要步骤包括创建自定义布局类,设置item数量,存储item信息,重写prepare和layoutAttributesForElements方法,以及在UIController中正确使用该布局。
摘要由CSDN通过智能技术生成

在这里插入图片描述

主要步骤:添加一个class继承UICollectionViewFlowLayout

  1. 添加一个itemCount:Int,用来设置item数量,在创建对象时要传入
  2. 添加一个数组属性,用来存放每个item的局部信息(item.frame)
  3. 重写prepare方法,设置每个item的frame,并存入数组
  4. 重写layoutAttributesForElements方法,并将存放item.frame信息的数组返回
//
//  UICollectionViewFlowLayout1.swift
//  snapkit-study
//
//  Created by YY on 2021/1/19.
//
 
import UIKit
 
class WaterFallLayout: UICollectionViewFlowLayout {
   
//    封装一个属性,用来设置item的个数
    let itemCount:Int
//    添加一个数组属性,用来存放每个item的布局信息
    var attributeArray:Array<UICollectionViewLayoutAttributes>?
//    实现必要的构造方法
    required init?(coder aDecoder: NSCoder) {
   
        itemCount = 0
        super.init(coder:aDecoder)
    }
//    自定义一个初始化构造方法
    init(itemCount:Int) {
   
        self.itemCount = itemCount
        super.init()
    }
    
    override func prepare() {
   
        //调用父类的准备方法
        super.prepare()
        //设置为竖直布局
        self.scrollDirection = .vertical
        //初始化数组
        attributeArray = Array<UICollectionViewLayoutAttributes>()
        //先计算每个item的宽度,设置为三列布局
        let WIDTH = (UIScreen.main.bounds.size.width-2 * self.minimumInteritemSpacing)/3
        //定义一个元组表示每一列的动态高度(决定有多少列)
        var queueHieght:(one:Int,two:Int, thrid:Int) = (0, 0, 0)
        //进行循环设
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值