更改UICollectionViewCell高度以适合UILabel

时间:2015-12-11 22:51:45

标签: ios swift uicollectionview

我试图让我的格子高度大小与标签一致。问题是标签文本是在cellForItemAtIndexPath中设置的,如果我理解正确,sizeForItemAtIndexPath会在cellForItemAtIndexPath之前运行。这是我到目前为止所尝试的:

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!
    }

我没有使用自动布局。

enter image description here

为什么细胞高度不会因标签而改变的任何建议?

2 个答案:

答案 0 :(得分:1)

这曾经是一个令人烦恼的问题,但如果您能够使用自动布局,它会变得非常容易。有关详细演练,请参阅this answer

答案 1 :(得分:0)

即使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

}
相关问题