我覺得這應該比現在更容易。我想要做的是爲每個收藏視圖的單元格設置不同的高度(具體取決於每個單元格內的標籤大小)。我正在使用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
子類的實例,以便甚至能夠啓動(這樣我就可以真正訪問標籤,並嘗試找出一個高度)一直停留在這幾個小時。。/
謝謝。這工作。看起來我應該能夠根據實際的單元計算高度,或者應該更直觀,但我想不是這種情況。 :( 謝謝! – SeeMeCode