我正在使用UICollectionViewCompostionalLayout在我的集合视图的某些部分中创建动态宽度、固定高度、标记单元格类型的布局.当我向数据库中的数组添加新字符串、将数组重新加载到数据源并执行集合视图重新加载数据时,单元格以一种不可预测的方式调整大小.有时它们调整大小以适合字符串的宽度,有时它们似乎使用单元格的估计宽度并截断字符串.对如何解决这个问题有什么建议吗?我已经在下面发布了一张gif.
以下是我的makelayout函数(简化并删除了不必要的代码行):
override func makeLayout() -> UICollectionViewLayout {
let layout = UICollectionViewCompositionalLayout(sectionProvider: { (sectionIndex, environment) -> NSCollectionLayoutSection? in
let itemSize = NSCollectionLayoutSize(widthDimension: .estimated(40), heightDimension: .absolute(40))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let inset: CGFloat = 10
item.contentInsets = NSDirectionalEdgeInsets(top: inset, leading: inset, bottom: inset, trailing: inset)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(40))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
group.interItemSpacing = NSCollectionLayoutSpacing.fixed(CGFloat(10))
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = CGFloat(10.0)
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20)
section.supplementariesFollowContentInsets = false
return section
})
let config = UICollectionViewCompositionalLayoutConfiguration()
config.scrollDirection = .vertical
config.interSectionSpacing = 10
layout.configuration = config
return layout
}
这是我自定义集合视图单元格
class CollectionViewCell: UICollectionViewCell {
lazy var textLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: "Stolzl-Regular", size: 12)
label.textAlignment = NSTextAlignment.left
label.backgroundColor = .clear //.red
label.textColor = .white
label.text = ""
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
label.lineBreakMode = NSLineBreakMode.byWordWrapping
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupLabel()
}
func setupLabel(){
addSubview(textLabel)
addConstraintsWithFormat("H:|-10-[v0]-10-|", views: textLabel)
addConstraintsWithFormat("V:|-10-[v0]-10-|", views: textLabel)
}
override func prepareForReuse() {
super.prepareForReuse()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}