菜鸟教程小白 发表于 2022-12-11 17:29:08

ios - Collection View 单元格大小取决于 UITextView


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

<pre><code>    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -&gt; CGSize {

    if (indexPath.row &lt; myComments!.count) {

      if let messageText = myComments!.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: , context: nil)
            return CGSizeMake(view.frame.width, estimatedFrame.height + 50)
      }
    }
    return CGSizeMake(view.frame.width, 100)

}
</code></pre>

<p>但是它并没有真正起作用。有时高度太大,有时太小,我仍然需要滚动。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>使用 TextView 的 sizeThatFits 方法。它精确计算 UITextView 需要的大小。 </p></p>
                                   
                                                <p style="font-size: 20px;">关于ios -Collection View 单元格大小取决于 UITextView,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/39430656/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/39430656/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - Collection View 单元格大小取决于 UITextView