You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在同一个UIViewController中垂直堆叠多个UICollectionView

问题根因
  • 未关闭translatesAutoresizingMaskIntoConstraints:使用纯代码Auto Layout约束前,必须手动将视图的该属性设为false,否则系统会自动基于初始frame生成约束,和你手动添加的约束冲突,导致自定义约束不生效
  • 约束不完整:两个CollectionView都只设置了单个top约束,缺少水平方向约束、高度/底部约束,系统无法计算正确的布局尺寸
  • 布局对象误用:两个CollectionView共用同一个UICollectionViewFlowLayout实例,且你当前设置的itemSize是Post列表的Cell尺寸,不符合Story栏的常规布局需求(Story栏通常为横向滚动、固定高度)
修正后代码
// 单独创建Story栏专属布局,适配横向滚动交互
let storyLayout = UICollectionViewFlowLayout()
storyLayout.scrollDirection = .horizontal
// 可根据你的Story Cell实际尺寸调整
storyLayout.itemSize = CGSize(width: 80, height: 80)
storyLayout.minimumLineSpacing = 12
storyLayout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)

storyCollectionView = StoryCollectionView(frame: .zero, collectionViewLayout: storyLayout)
// 禁用自动生成约束
storyCollectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(storyCollectionView)

// Post列表专属布局
let postLayout = UICollectionViewFlowLayout()
postLayout.itemSize = CGSize(width: view.frame.width, height: ((view.frame.width * 0.75) + (view.frame.width / 3 - 8.75) * 0.75) - 38)
postLayout.minimumLineSpacing = 0

postCollectionView = PostCollectionView(frame: .zero, collectionViewLayout: postLayout)
// 禁用自动生成约束
postCollectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(postCollectionView)

// 统一激活所有约束
NSLayoutConstraint.activate([
    // StoryCollectionView约束
    storyCollectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
    storyCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    storyCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
    storyCollectionView.heightAnchor.constraint(equalToConstant: 80), // 如需动态高度可后续更新此约束
    
    // PostCollectionView约束
    postCollectionView.topAnchor.constraint(equalTo: storyCollectionView.bottomAnchor),
    postCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    postCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
    postCollectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
])
补充说明

如果需要StoryCollectionView高度随内容自适应,可移除固定高度约束,在StoryCollectionView调用reloadData()后,更新其高度约束值为自身contentSize.height即可。

内容的提问来源于stack exchange,提问作者Brandon B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 12:42:01