【问题标题】:Dynamic height for UICollectionViewCellUICollectionViewCell 的动态高度
【发布时间】:2016-10-10 09:49:01
【问题描述】:

我希望根据 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 的单元格高度。 但实际上我想要根据内容的单元格高度。 我怎样才能做到这一点? 任何帮助表示赞赏。提前致谢

【问题讨论】:

  • 标签中显示的字符串长度是否有最大限制?
  • 不,我没有应用任何最大限​​制
  • 那么单元格的最小高度呢?某些单元格的字符串是否有可能为空?
  • @NeelamPursnani,要做到这一点(2016 年)仍然非常困难——这并不容易。准备好几周的工作来擅长这个,你可以从大量关于它的文章中的任何一个开始......stackoverflow.com/questions/18746929
  • 无字符串单元格不能为空。我正在尝试创建聊天窗口

标签: ios swift3


【解决方案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
}

请务必将 label 的顶部/底部/左侧/右侧边距补到 cell

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 2014-09-20
    • 2014-04-02
    • 1970-01-01
    • 2021-05-10
    相关资源
    最近更新 更多