ios - UICollectionViewCell 的动态高度

标签 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

最佳答案

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

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
}

请务必将 label 的上/下/左/右页边距补偿到 cell

关于ios - UICollectionViewCell 的动态高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39955597/

相关文章:

ios - 在nativescript项目中使用第3方、 native SDK - 框架似乎不是动态框架

ios - 使用 iOS 地理围栏跟踪多个(20 多个)位置

ios - 从另一个类访问属性

ios - 获取使用 Storyboard创建的 View Controller 的属性

ios - swift3 中的 Button.titleLabel 错误

ios - 如何禁用 `MGLSymbolStyleLayer` 的集群化功能?

iphone - 如何在服务器上动态上传图片?

ios - 谷歌地图不适合 subview

swift - NSAsynchronousFetchRequest 可能的内存泄漏

ios - 回调 swift 3 中的标签未更改