【问题标题】:Collection View Cell Size Dependent on UITextView集合视图单元格大小取决于 UITextView
【发布时间】:2017-01-18 17:32:33
【问题描述】:

我有一个UICollectionView 和一个Cell,其中包含一个UITextView。我希望单元格的大小取决于 TextView 的高度(因此不需要滚动并且所有文本始终可见)。 我正在尝试这个:

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

    if (indexPath.row < myComments!.count) {

        if let messageText = myComments![indexPath.row].text  {
            let size = CGSizeMake(self.view.frame.width / 2, 100)
            let options = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin)
            let estimatedFrame = NSString(string: messageText).boundingRectWithSize(size, options: options, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(14)], context: nil)
            return CGSizeMake(view.frame.width, estimatedFrame.height + 50)
        }
    }
    return CGSizeMake(view.frame.width, 100)

}

但是它并没有真正起作用。有时高度太大,有时太小,我仍然需要滚动。

【问题讨论】:

    标签: ios swift uicollectionview height uicollectionviewcell


    【解决方案1】:

    使用 TextView 的 sizeThatFits 方法。它精确计算 UITextView 需要的大小。

    【讨论】: