我已经实现了collectionview
水平滚动。当启用滚动时它工作正常。但是,当禁用滚动并且流程更改为垂直时,仅显示第一行并且 Collection View 高度不会增加。
问:- 禁用滚动时如何获得 Collection View 的完整高度?
我尝试了以下代码来获取高度,它返回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
}
最佳答案
我遇到了类似的问题。我的解决方案是向 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)
关于ios - UICollectionview动态高度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50228280/