iOS 自定义 UICollectionView 拼图布局 + 布局切换动画实践

🧩 iOS 自定义 UICollectionView 拼图布局 + 布局切换动画实践

本文只讲两件事: 👉 如何自定义 UICollectionView 布局 👉 如何优雅地切换布局并处理动画问题


✨ 一、为什么要自定义布局?

系统的 UICollectionViewFlowLayout 有一个明显限制:

👉 只能做规则网格(grid)布局

但很多场景需要:

  • 拼图布局(不规则)
  • 瀑布流变种
  • 卡片混排

例如👇

css 复制代码
┌───────────────┐
│       A       │
├───────┬───────┤
│   B   │   C   │
└───────┴───────┘

👉 这种布局 FlowLayout 是做不了的


🧠 二、自定义布局核心原理

自定义布局本质只做三件事:

1️⃣ 计算每个 cell 的 frame

objectivec 复制代码
UICollectionViewLayoutAttributes

2️⃣ 返回可见区域的 attributes

swift 复制代码
override func layoutAttributesForElements(in rect: CGRect)

3️⃣ 告诉 collectionView 内容尺寸

swift 复制代码
override var collectionViewContentSize: CGSize

🔥 三、实现一个拼图布局(MosaicLayout)

核心代码

swift 复制代码
class MosaicLayout: UICollectionViewFlowLayout {
​
    var layoutAttributes: [UICollectionViewLayoutAttributes] = []
    var contentSize: CGSize = .zero
​
    override func prepare() {
        super.prepare()
​
        guard let collectionView = collectionView else { return }
​
        layoutAttributes.removeAll()
​
        let count = collectionView.numberOfItems(inSection: 0)
        guard count > 0 else { return }
​
        let width = collectionView.bounds.width
        let height = width
​
        let frames: [CGRect] = [
            CGRect(x: 0, y: 0, width: 1, height: 0.6),
            CGRect(x: 0, y: 0.6, width: 0.5, height: 0.4),
            CGRect(x: 0.5, y: 0.6, width: 0.5, height: 0.4)
        ]
​
        for (index, relativeFrame) in frames.enumerated() {
​
            let frame = CGRect(
                x: relativeFrame.origin.x * width,
                y: relativeFrame.origin.y * height,
                width: relativeFrame.width * width,
                height: relativeFrame.height * height
            )
​
            let attr = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: index, section: 0))
            attr.frame = frame
            layoutAttributes.append(attr)
        }
​
        contentSize = CGSize(width: width, height: height)
    }
​
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return layoutAttributes.filter { $0.frame.intersects(rect) }
    }
​
    override var collectionViewContentSize: CGSize {
        return contentSize
    }
}

🎬 五、布局切换动画

php 复制代码
collectionView.setCollectionViewLayout(newLayout, animated: true)

⚠️ 六、崩溃问题

swift 复制代码
The invalidation context is not an instance of UICollectionViewFlowLayoutInvalidationContext

解决方案

php 复制代码
collectionView.setCollectionViewLayout(newLayout, animated: false)
collectionView.reloadData()

🎯 七、总结

👉 自定义布局 = 自己控制 frame 👉 动画关键 = 避免同时更新数据源


如果你觉得有用,欢迎点赞 👍

相关推荐
Chrischaan13 分钟前
做 AI 塔罗小程序时,我为什么不让大模型自己抽牌:一次上线复盘
前端
骑着蜗牛撵大象32743 分钟前
LangChain 工具调用从声明到闭环:给智能体接上真实的手脚
前端
数据掘金1 小时前
百度统计后台页面数据异常?从手动调用时机开始排查
前端
hunteritself1 小时前
10 层 4K 实时剪辑,国产工作站进入广电制作核心
大数据·前端·人工智能·深度学习·transformer
踩着两条虫1 小时前
我在浏览器里“盖”了一个村:Vue + Three.js 大屏开发踩坑记
前端·vue.js·three.js
mbshqqb1 小时前
TypeScript基础教程之同步生成器
前端·javascript·typescript
嘟嘟同学和妮妮同学1 小时前
【升级】一个中国历史可视化站:皇帝时间线梳理、古代思想流派、诗词鉴赏 (2)
前端·html
暗夜行者之光2 小时前
LangGraph + MCP 实战:构建"自然语言查数据"的 ChatBI Agent
前端·后端
一tiao咸鱼2 小时前
还在手动海投?我做了个 AI 求职助手,自动筛选 BOSS 职位再精准投递
前端·后端·面试
尤水就下2 小时前
🔥预热:在线文档的 block 架构是如何实现的(未完待续...)
前端·javascript·架构