繁体   English   中英

更改UICollectionViewCell高度以适合UILabel

[英]Change UICollectionViewCell height to fit UILabel

我想让我的细胞高度大小与标签一致。 问题是标签文本在cellForItemAtIndexPath设置,如果我理解正确, sizeForItemAtIndexPathcellForItemAtIndexPath之前运行。 这是我到目前为止尝试过的事情:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        let imageCell = collectionView.dequeueReusableCellWithReuseIdentifier("imageCell", forIndexPath: indexPath) as? CollectionViewCell

        imageCell!.imageText.text = post.text // This set the UICollectionView Cell text

        imageCell!.frame.size.height = (imageCell!.frame.size.height) + (imageCell!.imageText.frame.size.height)

        return imageCell!
    }

我没有使用自动布局。

在此输入图像描述

任何建议为什么细胞高度不会根据标签变化?

这曾经是一个令人烦恼的问题需要解决,但如果你能够使用自动布局,它会变得非常容易。 请参阅此答案以获得详尽的演练。

即使sizeForItemAtIndexPath首先运行,也就是设置单元格大小的地方。 cellForItemAtIndexPath无法更改大小。

sizeForItemAtIndexPath您需要找出每个单元格的图像大小,然后返回该大小。

像这样的东西:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let imageCell = collectionView.cellForItemAtIndexPath(indexPath) as! CollectionViewCell
    let size = CGSize(width: imageCell.frame.width, height: imageCell.frame.size.height + imageCell.imageText.frame.size.height)
    return size

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM