UICollectionView聊天气泡大小

时间:2017-10-20 19:13:00

标签: swift uicollectionview uicollectionviewcell xcode9

我目前正在使用Xcode 9中的聊天应用程序。我没有使用stroyboards以编程方式执行所有操作。对于聊天室"我正在使用 UICollectionViewController ,我希望单元格调整为文本的大小。我正在计算像这样的细胞大小:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let size = CGSize(width: 250, height: 1000)
    let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
    let estimatedFrame = NSString(string: messages[indexPath.item].content as! String).boundingRect(with: size, options: options, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18)], context: nil)

    return CGSize(width: view.frame.width, height: estimatedFrame.height + 45)
}

所以我基本上只是计算文本的大小,然后将其作为单元格高度返回。这适用于短文本,但只要文本超过6行,就会丢失最后一行。从那时起,计算出的高度是错误的,因为如果我只是设置一个恒定的高度,文本显示。任何人都可以发现错误,或者我应该使用其他方法在UICollectionView中自行调整聊天气泡大小?

0 个答案:

没有答案
相关问题