2015-12-11 153 views
3

我正在嘗試使我的單元格高度尺寸適合標籤。問題是標籤文本設置在cellForItemAtIndexPath中,如果我理解正確,sizeForItemAtIndexPathcellForItemAtIndexPath之前運行。這是我迄今試過的東西:更改UICollectionViewCell高度以適合UILabel

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

爲什麼不根據標籤上的細胞高度的變化有什麼建議?

回答

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 

} 
+0

問題是我該怎麼做呢? –

+0

我更新了,但實際上,它與您的代碼相同,只是移至其他功能。 – Tim

+0

我收到錯誤消息:http://s27.postimg.org/vzvdugloj/Screen_Shot_2015_12_12_at_02_04_33.png - 您是否還添加了'imageCell!.frame.size.height ='? –

1

過去,這是解決一個惱人的問題,但如果你能使用自動佈局它變得明顯更容易。請參閱this answer進行全面的演練。

+0

問題我沒有使用自動佈局:http://s8.postimg.org/zcok16nsl/Screen_Shot_2015_12_12_at_00_42_49.png –