使用Compositional Layout+Stage Manager时应用崩溃,报错无效绝对维度inf
问题分析与解决
崩溃原因
报错Invalid absolute dimension: inf. The dimension must be a finite value.说明代码里的cellWidth或cellHeight在Stage Manager调整窗口尺寸等场景下,变成了无穷大(inf),导致Compositional Layout无法生成有效的布局尺寸。
解决方法
1. 强制保证尺寸值有效
在使用cellWidth和cellHeight前添加边界校验,避免出现非有限值:
// 限制尺寸在合理区间,比如最小10pt,最大不超过当前屏幕宽高 let safeCellWidth = max(min(cellWidth, UIScreen.main.bounds.width), 10) let safeCellHeight = max(min(cellHeight, UIScreen.main.bounds.height), 10) let itemSize = NSCollectionLayoutSize(widthDimension: .absolute(safeCellWidth), heightDimension: .absolute(safeCellHeight)) let item = NSCollectionLayoutItem(layoutSize: itemSize)
2. 改用相对/自适应尺寸替代绝对尺寸
绝对尺寸在窗口动态变化时稳定性差,推荐用相对尺寸或预估尺寸:
// 示例:让item宽度占group的1/3,高度用预估自适应 let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1/3), heightDimension: .estimated(80)) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(80)) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
3. 窗口尺寸变化时重新生成布局
在窗口大小改变时,重新计算布局参数并刷新UICollectionView布局:
override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() // 重新计算cellWidth、cellHeight等参数 let updatedLayout = createCollectionViewLayout() // 你的布局创建方法 collectionView.setCollectionViewLayout(updatedLayout, animated: true) }
内容的提问来源于stack exchange,提问作者iroh
相关产品推荐
相关产品推荐

