我使用了比较简单的合成布局,它可以工作,但在某些情况下,我的UICollectionView中最后一两个单元格的宽度似乎被破坏了。
我的CollectionView由动态宽度和静态高度的单元格组成。我可以事先计算高度,因为我的单元格基本上是UILabel加背景UIView加topleftrightbottom约束(每个约束都有UIPriority(1000))。
topicBackView = UIView()
topicBackView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(topicBackView)
topicLabel = MyLabel()
topicLabel.translatesAutoresizingMaskIntoConstraints = false
topicLabel.numberOfLines = 0
topicLabel.font = cs.usualFont
topicLabel.textColor = UIColor.black
topicLabel.textAlignment = .center
contentView.addSubview(topicLabel)
let tpp = topicBackView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0)
tpp.priority = UILayoutPriority(1000)
tpp.isActive = true
以此类推。
我知道UILabel的字体,我知道所有约束条件的常量,所以很容易预测单元格的高度。
正因为如此,我的布局看起来是这样的。
func giveMeFreeTagsLayout() -> UICollectionViewLayout {
let estimatedHeight: CGFloat = topicsCellCollectionHeight
let estimatedWidth: CGFloat = 200
let itemSize = NSCollectionLayoutSize(widthDimension: .estimated(estimatedWidth),
heightDimension: .absolute(estimatedHeight))
//height is absolute because I know it, and in some cases-not in this one, though-I have to calculate the height of UICollectionView
let item = NSCollectionLayoutItem(layoutSize: itemSize)
item.edgeSpacing = NSCollectionLayoutEdgeSpacing(leading: .fixed(0), top: .fixed(8), trailing: .fixed(8), bottom: .fixed(8))
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
heightDimension: .estimated(estimatedHeight))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize,
subitems: [item])
group.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 20, trailing: 0)
let layout = UICollectionViewCompositionalLayout(section: section)
return layout
}
问题是,它在iPhone 11的模拟器中可以工作,但当我试图在更小的屏幕上模拟时(在我的例子中,iPad Air第三代与iPhone兼容),这个集合视图似乎被破坏了。
在这种情况下,最后一两个单元格的宽度被打破,我不知道为什么。
这里到底发生了什么?