我已经实现了collectionview
水平滚动。启用滚动时,它工作正常。但是,当禁用滚动并且流程更改为垂直时,仅显示第一行,并且不会增加集合视图高度。
问: - 如果禁用滚动,如何才能获得集合视图的全高?
我尝试了以下代码来获取高度,然后返回30.0
。
let height = self.collectionTags.collectionViewLayout.collectionViewContentSize.height; // 30.0
这个返回0.0
let height = self.collectionTags.contentSize.height // 0.0
这是collectionview布局代码
if let flowLayout = collectionTags.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = CGSize(width: 1, height: 30.0)
flowLayout.itemSize = UICollectionViewFlowLayoutAutomaticSize
}
答案 0 :(得分:0)
我遇到了类似的问题。我的解决方案是将height constraint
添加到collectionView并根据我想要显示的项目计算其高度。这是我创建的一个片段:
// Items that will be displayed inside CollectionView are called tags here
// Total tags width
var tagWidth:CGFloat = 0
// Loop through array of tags
for tag in self.tagsArray {
// Specifying font so we can calculate dimensions
let tagFont = UIFont(name: "Cabin-Bold", size: 17)!
let tagAttributes: [String : Any]? = [
NSFontAttributeName: tagFont,
NSForegroundColorAttributeName: UIColor.white,
]
// Get text size
let tagString = tag as NSString
let textSize = tagString.size(attributes: tagAttributes ?? nil)
// Add current tag width + padding to the total width
tagWidth += (textSize.width + 10)
}
// Calculate number of rows
var totalRows = tagWidth / (self.bounds.width - 40)
totalRows = totalRows.rounded(.up)
// Calculate height and apply it to the CollectionView height constraint
estimatedCollectionViewHeight = Float(CGFloat(totalRows * 29))
collectionViewHeight.constant = CGFloat(estimatedCollectionViewHeight)