UICollectionViewCell 自动大小的两种常用方式

2023-05-16

方法一:自动计算

override func viewDidLoad() {
   super.viewDidLoad()

   if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
      flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
    }
}

class YourCustomCollectionViewCell: UICollectionViewCell {
    override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
        layoutAttributes.size = self.intrinsicContentSize
        return layoutAttributes 
    }

    override var intrinsicContentSize: CGSize {
        return self.someView.viewSize()
    }

    // ......

}

方法二:手动计算

protocol SizeableCollectionViewCell {
    func fittedSize(forConstrainedSize size: CGSize)->CGSize
}

class YourCustomCollectionViewCell: UICollectionViewCell, SizeableCollectionViewCell {

    @IBOutlet private var mTitle: UILabel!
    @IBOutlet private var mDescription: UILabel!
    @IBOutlet private var mContentView: UIView!
    @IBOutlet private var mTitleTopConstraint: NSLayoutConstraint!
    @IBOutlet private var mDesciptionBottomConstraint: NSLayoutConstraint!

    func fittedSize(forConstrainedSize size: CGSize)->CGSize {

        let fittedSize: CGSize!

        //if height is greatest value, then it's dynamic, so it must be calculated
        if size.height == CGFLoat.greatestFiniteMagnitude {

            var height: CGFloat = 0

            /*now here's where you want to add all the heights up of your views.
              apple provides a method called sizeThatFits(size:), but it's not 
              implemented by default; except for some concrete subclasses such 
              as UILabel, UIButton, etc. search to see if the classes you use implement 
              it. here's how it would be used:
            */
            height += mTitle.sizeThatFits(size).height
            height += mDescription.sizeThatFits(size).height
            height += mCustomView.sizeThatFits(size).height    //you'll have to implement this in your custom view

            //anything that takes up height in the cell has to be included, including top/bottom margin constraints
            height += mTitleTopConstraint.constant
            height += mDescriptionBottomConstraint.constant

            fittedSize = CGSize(width: size.width, height: height)
        }
        //else width is greatest value, if not, you did something wrong
        else {
            //do the same thing that's done for height but with width, remember to include leading/trailing margins in calculations
        }

        return fittedSize
    }
}

class YourViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    private var mCustomCellPrototype = UINib(nibName: <name of the nib file for your custom collectionviewcell>, bundle: nil).instantiate(withOwner: nil, options: nil).first as! SizeableCollectionViewCell

    private var mDataSource: [CustomModel]

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath)->CGSize {

        //bind the prototype cell with the data that corresponds to this index path
        mCustomCellPrototype.bind(model: mDataSource[indexPath.row])    //this is the same method you would use to reconfigure the cells that you dequeue in collectionView(:cellForItemAt:). i'm calling it bind

        //define the dimension you want constrained
        let width = UIScreen.main.bounds.size.width - 20    //the width you want your cells to be
        let height = CGFloat.greatestFiniteMagnitude    //height has the greatest finite magnitude, so in this code, that means it will be dynamic
        let constrainedSize = CGSize(width: width, height: height)

        //determine the size the cell will be given this data and return it
        return mCustomCellPrototype.fittedSize(forConstrainedSize: constrainedSize)
    }
}

参考

iOS自定义View 控件自动计算size能力icon-default.png?t=LA92https://blog.csdn.net/qq_14920635/article/details/115318381

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

UICollectionViewCell 自动大小的两种常用方式 的相关文章

随机推荐

  • grafana 画富集多个指标 label 的表格

    下午5点 xff1a 老哥 xff0c 今天把业务趋势图搞出来吧 一 怎么画表格 我们的需要是做下面的视图 xff0c 他是一个表格 xff0c 而且有着多个数据源 添加图表 填入数据 xff0c 展示原始图形 转换为 table 只显示最
  • [golang] 实现 jwt 方式登录

    1 Jwt 和 Session 登录方案介绍 JSON Web Token xff08 缩写 JWT xff09 是目前流行的跨域认证解决方案 原理是生存的凭证包含标题 header xff0c 有效负载 payload 和签名组成 用户信
  • Stochastic Light Culling for VPLs on GGX Microsurfaces论文研读

    前言 好久没写博客了 xff0c 今天来共享一下最近研读的一篇论文吧 xff0c 文章中 pdf 为参考文献可自行谷歌学术下载 因为本人还是个图形学菜鸟 xff0c 所以有什么问题希望大家多多指正 Stochastic Light Cull
  • 瞎更新,container_cpu_usage_seconds_total{job=“cadvisor“} 怎么没有啦

    一 基本介绍 1 1 概论 1 1 1 故事背景 今天在同步其他团队的 grafana 监控大盘时 xff0c Prometheus 服务报告说不能找到名为 container cpu usage seconds total job 61
  • Prometheus MySQL 性能监控

    一 介绍 Prometheus 是一种开源的监控系统和时序数据库 xff0c 旨在收集和处理大量数据并提供可视化 监控警报等功能 它支持多种语言 多种部署方式 xff0c 并且非常灵活 xff0c 而且社区支持非常活跃 xff0c 为用户提
  • 二、nodeJS 项目架构详解(app.js + Express + Http)

    参考 xff1a https www cnblogs com ostrich sunshine p 7474471 html 其中重点文件 文件夹说明 xff1a techNode xff1a bin www 启动运行 xff08 服务端口
  • centos 安装freeswitch

    首先安装freeswitch的运行库 更新yum yum update 安装依赖 yum install y git gcc c 43 43 wget alsa lib devel autoconf automake bison broad
  • Visio、Matlab高清图片插入word文档的几种方法。

    2023 3 30 直接参考这两个就行了 xff0c 不用花里胡哨的 MATLAB 1 重要的第一步 xff0c 另存为png图片 xff1b 2 导出之前先设置分辨率 xff0c 很多期刊要求600dpi 这一步很关键 Visio 1 重
  • CTF Crypto---RSA NC不互素

    题目 span class token keyword from span Crypto span class token punctuation span Util span class token punctuation span nu
  • 看一看Ubuntu的目录结构

    先了解一下Ubuntu的目录结构 xff0c 对于后面学习Ubuntu软件安装和使用都有帮助 一 Linux没有盘符这个概念 Windows存在多个驱动器盘符 xff0c 每个盘符形成多个树形并列的情形 xff0c Linux没有盘符这个概
  • 【C语言】——结构体进阶:结构体的内存对齐(超详细)

    前言 xff1a 上一篇已经讲了结构体的基本用法 相信各位小伙伴以经学会怎么使用 但是还有一个问题没有弄明白 结构体到底多大 xff0c 占内存空间多不多 xff0c 以经系统到底怎么访问结构体内的数据的 接下来 xff0c 详细分析一下结
  • [OpenCV实战]15 基于深度学习的目标跟踪算法GOTURN

    目录 1 什么是对象跟踪和GOTURN 2 在OpenCV中使用GOTURN 3 GOTURN优缺点 4 参考 在这篇文章中 xff0c 我们将学习一种基于深度学习的目标跟踪算法GOTURN GOTURN在Caffe中搭建 xff0c 现在
  • **在Linux的shell脚本里激活conda 虚拟环境**

    在Linux的shell脚本里激活conda 虚拟环境 之前突发其想 xff0c 既然在命令行可以通过conda activate tf激活tf的虚拟环境 xff0c 那么能不能写个脚本实现呢 xff1f 费了好大劲 xff0c 发现并不行
  • Hierarchical Russian Roulette for Vertex Connections论文研读

    第二篇论文研读文章了 xff0c 虽然依旧很菜 xff0c 但这一篇开始就相对轻松一点了 文档种有些问题 xff0c 其中所有 实时 应该替换为 高效 Hierarchical Russian Roulette for Vertex Con
  • ARM通用中断控制器GIC之中断控制

    在阅读本章之前 xff0c 可以参考笔者之前关于GIC的一些描述 xff1a ARM通用中断控制器GIC generic Interrupt Controller 简介 ARM架构Generic Interrupt Controller G
  • 最小生成树之Kruskal算法

    给定一个无向图 xff0c 如果它任意两个顶点都联通并且是一棵树 xff0c 那么我们就称之为生成树 Spanning Tree 如果是带权值的无向图 xff0c 那么权值之和最小的生成树 xff0c 我们就称之为最小生成树 MST Min
  • xcode11解决:xcode multiple commands produce .../xxx/Assets.car

    最近在xcode 11上使用pod碰到一个问题 xff0c Assets car被生成多次 问题如下 xff1a Multiple commands produce 39 Users luowei Library Developer Xco
  • 算法 —— 冒泡排序

    冒泡排序 冒泡排序是比较两个相邻元素 xff0c 如果它们不符合预期的顺序就交换的一个排序过程 冒泡排序就像水中气泡上升到水面的运动一样 xff0c 数组的每个元素在每次迭代中都把当前迭中最大 或最小 的元素移动到最后 xff0c 因此被称
  • UICollectionView viewForSupplementaryElementOfKind 不调用

    发现UICollectionView 的 方法不调用 func collectionView collectionView UICollectionView viewForSupplementaryElementOfKind kind St
  • UICollectionViewCell 自动大小的两种常用方式

    方法一 xff1a 自动计算 override func viewDidLoad super viewDidLoad if let flowLayout 61 collectionView collectionViewLayout as U