【问题标题】:How to make UICollectionview cell height dynamic?如何使 UICollectionview 单元格高度动态化?
【发布时间】:2016-08-04 05:32:09
【问题描述】:

我有一个UIcollectionview。 Collectionview 有一些单元格。在 CollectionviewCell 里面有一个文本视图。 textview 的内容是动态的。所以单元格高度应该是动态的。

怎么做?

【问题讨论】:

  • 您始终可以为此创建自定义布局,如果您更改某些单元格的高度,您可能需要更改一些其他单元格的实际位置,这些单元格将与较大的单元格重叠 - 并且自定义布局是处理这种情况的理想场所。

标签: ios swift uicollectionview uicollectionviewcell


【解决方案1】:

1-添加UICollectionViewDelegateFlowLayout 协议。
2-通过在您的ViewController 中实现sizeForItemAtIndexPath 方法来符合协议。
3-使用单元格的索引来获取您拥有的文本并计算它的高度和宽度。

class ViewController: UIViewController,UICollectionViewDelegateFlowLayout{

  func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
     let constraintRect = CGSize(width: self.view.frame.size.width, height: CGFloat.max)
     let data = myTextArray[indexpath.row];
     let boundingBox = data.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont(name: Constants.strings.fontName, size: 30)!], context: nil)
     return CGSizeMake(boundingBox.width, boundingBox.height); //(width,hight)
  }

}

【讨论】:

  • 谢谢!但是最后一个单元格的行为不同。所有单元格都按预期绘制,但最后一个单元格的前导比其他单元格多。有什么建议吗?
【解决方案2】:

使用sizeForItemAtIndexPath中的NSAttributedString来计算矩形的高度和宽度:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    let attString = NSAttributedString(string: self.rows[indexPath.row], attributes: [NSFontAttributeName: UIFont.systemFontOfSize(15.0)])
    var r: CGRect = attString.boundingRectWithSize(CGSizeMake(self.collectionView.bounds.size.width, CGFLOAT_MAX), options: .UsesLineFragmentOrigin, context: nil)

    return r.size

}

【讨论】:

  • 谢谢!但是最后一个单元格的行为不同。所有单元格都按预期绘制,但最后一个单元格的前导比其他单元格多。有什么建议吗?
  • 如果 textView 使用不同的字体和大小,您必须将 'NSFontAttributeName' 添加到 'NSAttributedString' 以计算正确的大小
【解决方案3】:

1) 覆盖collectionflowlayout委托方法

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSizeMake(50, 50); //(width,hight)
}

2) 在上述方法中,计算包含动态长度的 textview 的高度,并将该值添加到您的固定高度中。 Ex. cellHeight = 100 + textview height. //100 is height which not contain textview height.

3) 计算高度后,用上述方法替换

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
            return CGSizeMake(50, dynamicheight); //(width,hight)
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多