ios - UICollectionview动态高度问题

标签 ios swift uicollectionviewcell uicollectionviewlayout

我想要实现以下结果 enter image description here

我已经实现了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/

相关文章:

objective-c - Objective C中的简单字符串连接

ios - 我正在尝试使用圆角半径来查看放置在 UITableView 内的内容。这对我不起作用

ios - 从音频文件中获取正弦波显示

ios - UICollectionCell 调用 CollectionViewController 中的方法

ios - 4.4 和 5.5 英寸的 UICollectionViewCell 动态尺寸调整

ios - 如何在集合单元格中重绘动态大小的 UIView

ios - 如何在加载 View 后自动隐藏状态栏

ios - 如何实现直接改变字体颜色的效果?

ios - 在Watch App中访问一类iPhone应用程序

swift - 在 SWIFT 的表格 View 中填充自定义单元格时出错