【问题标题】:UICollectionview dynamic height issueUICollectionview 动态高度问题
【发布时间】:2018-05-08 07:34:37
【问题描述】:

我想达到以下结果

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

【问题讨论】:

  • 我想你想得到像输出一样的令牌字段。请看this

标签: ios swift uicollectionviewcell uicollectionviewlayout


【解决方案1】:

我遇到了类似的问题。我的解决方案是将height constraint 添加到collectionView 并根据我想要显示的项目计算它的高度。这是我创建的一个 sn-p:

// 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)

【讨论】:

    猜你喜欢
    • 2019-10-12
    • 1970-01-01
    • 2020-07-09
    • 2014-07-30
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    相关资源
    最近更新 更多