2015-06-22 61 views
0

我覺得這應該比現在更容易。我想要做的是爲每個收藏視圖的單元格設置不同的高度(具體取決於每個單元格內的標籤大小)。我正在使用sizeForItemAtIndexPath,但麻煩是在單元格創建之前計算出高度。如何爲每個UICollectionViewCell設置不同的高度

我現在擁有的一切:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 

    // target width of each cell - widht of the collectionView 
    let targetWidth: CGFloat = collectionView.frame.width - 20.0 

    // setup a prototype cell 
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCustomCellIdentifier", forIndexPath: indexPath) as! MyCustomCell 

    // for the sake of simplicity, let's just assume data is coming from somewhere else 
    cell.nameLabel.text = data.name 
    cell.notesLabel.text = data.notes 

    // resize - layoutSubviews in LocationCell controller 
    cell.layoutIfNeeded() 

    // get the size based on constraints 
    var size = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) 

    // force width 
    size.width = targetWidth 

    return size 
} 

什麼不工作是dequeueReusableCellWithReuseIdentifier。我猜這是因爲UICollectionViewCell尚未公佈?我也嘗試registerClass來得到那個,但是這似乎也不起作用。 :(

有沒有一種更簡單的方法來完成這一切?我需要做的是找出它在創建之前的高度是多少,我需要一個UICollectionViewCell子類的實例,以便甚至能夠啓動(這樣我就可以真正訪問標籤,並嘗試找出一個高度)一直停留在這幾個小時。。/

回答

1

使用這種方法

func heightForComment(comment:NSString,font: UIFont, width: CGFloat) -> CGFloat { 
     let rect = NSString(string: comment).boundingRectWithSize(CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) 
     return ceil(rect.height) 
} 
+0

謝謝。這工作。看起來我應該能夠根據實際的單元計算高度,或者應該更直觀,但我想不是這種情況。 :( 謝謝! – SeeMeCode

1

這不是做到這一點的正確方法,但對我的作品

使用本函數來獲得文本的大小

func labelSize(texto: NSString) -> CGRect { 
     var atributos = [NSFontAttributeName: UIFont.systemFontOfSize(17)] 
     var labelSize = texto.boundingRectWithSize(CGSizeMake(280, CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: atributos, context: nil) 
     return labelSize 
    } 
+0

這樣的聲音可能會奏效,所以謝謝。我只是擔心這會在複雜的佈局中變得非常混亂。因爲有不同大小的單元格在整個地方使用集合視圖,所以必須有一種方法。 – SeeMeCode

相關問題