UICollectionViewCell的动态高度

时间:2016-10-10 09:49:02

标签: ios swift3

我想要TextView中的文本动态单元格大小,   这是我的代码

        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
        {
            return DataArray.count
        }
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
        {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? CustomCollectionViewCell

            let fixedWidth = cell?.TextView.frame.size.width
            cell?.TextView.sizeThatFits(CGSize(width: fixedWidth!, height: CGFloat.greatestFiniteMagnitude))
            let newSize = cell?.TextView.sizeThatFits(CGSize(width: fixedWidth!, height: CGFloat.greatestFiniteMagnitude))
            var newFrame = cell?.TextView.frame
            newFrame?.size = CGSize(width: max((newSize?.width)!, fixedWidth!), height: (newSize?.height)!)
            cell?.TextView.frame = newFrame!
            TextViewFrame = newFrame!
            cell?.TextView.text = DataArray[indexPath.row] as? String
            return cell!
        }
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
        {

            return CGSize(width: CV.frame.size.width, height: 200)
        }

这里我给了200个固定大小的单元格。它给我输出如下 它为小内容和大内容提供了单元格高度200。 但实际上我想要根据内容的单元格高度。 我怎样才能实现这一目标? 任何帮助表示赞赏。提前致谢 enter image description here

1 个答案:

答案 0 :(得分:1)

一旦知道了要显示的文本的边界矩形,就可以找到单元格的高度。

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

    let text = "String that you want to show in the label inside the cell"
    let boundingRect = NSString(string: text).boundingRectWithSize(CGSizeMake(collectionView.bounds.width, 1000),
                                                                   options: .UsesLineFragmentOrigin,
                                                                   attributes: [NSFontAttributeName: UIFont.systemFontOfSize(11.0)],
                                                                   context: nil)

    let size = CGSizeMake(collectionView.bounds.width, ceil(boundingRect.height))

    return size
}

请务必弥补labelcell的上/下/左/右边距。