gpt4 book ai didi

swift - 组合布局和 splinter 的自定大小的单元格

转载 作者:行者123 更新时间:2023-12-05 02:07:42 25 4
gpt4 key购买 nike

我使用的是相对简单的组合布局,它确实有效,但在某些情况下,我的 UICollectionView 中的最后一两个单元格的宽度似乎不正确。

我的 collectionView 由具有动态宽度和静态高度的单元格组成。我可以预先计算高度,因为我的单元格基本上是 UILabel 加上背景 UIView 加上上/左/右/下约束(每个都有 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 上的模拟器中运行,但是当我尝试在较小的屏幕(在我的例子中是与 iPhone 兼容的第 3 代 iPad Air)上模拟时,这个 collectionView 似乎被破坏了。

在这种情况下,最后一两个单元格的宽度变窄了,我不知道为什么:

Bad one

应该是这样的: Good one (works like a charm)

这里发生了什么?

最佳答案

让 estimatedWidth: CGFloat = 200把它改成 50 就可以了

关于swift - 组合布局和 splinter 的自定大小的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61497430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com