簡體   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