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 👉 动画关键 = 避免同时更新数据源


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

相关推荐
yzy853 小时前
Vue中下载或打开文件的JavaScript方法
前端·javascript·vue
用户298698530143 小时前
在 React 中用 JavaScript 将 Word 转换为文本
前端·javascript·react.js
计算机魔术师3 小时前
马斯克称 Grok 4.7 使 xAI 在智能体编码领域位列第三
前端
摸鱼仙人~3 小时前
前端秋招异步手写题系统刷题路线:从 Promise 到 Pipeline、LazyMan 与并发控制
前端
秋天的一阵风3 小时前
⚡上线 24 小时,13% 的付费团队连夜换到 Jev:它到底什么来头?
前端·人工智能·ai编程
程序员若风3 小时前
CSRF攻击原理介绍和利用-腾讯云开发者社区
前端·网络·安全·web安全·网络安全·csrf攻击·腾讯云开发者社区
风尘小子3 小时前
node.js系列:process配置
前端·node.js
恋猫de小郭3 小时前
AndroidX 新增 Security State ,支持可编程的系统安全状态查询
android·前端·flutter
IT_陈寒4 小时前
Redis大key删除引发的服务雪崩,这次我真记住了
前端·人工智能·后端
IMPYLH4 小时前
HTML 的 <style> 元素
前端·html