0

我有以下代码,它将集合视图放入一列或两列,具体取决于屏幕的大小:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let size = collectionView.frame.width
    if (size > 500) {
        return CGSize(width: (size/2) - 8, height: (size/2) - 8)
    }
    return CGSize(width: size, height: size)
}

我想修改这个,所以高度取决于reuseIdentifier。我使用了两个 - 设置如下:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let diceRoll = Int(arc4random_uniform(2) + 1)
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("profileViewCell", forIndexPath: indexPath)
    if(diceRoll == 1) {
        cell = collectionView.dequeueReusableCellWithReuseIdentifier("profileChartViewCell", forIndexPath: indexPath)
    }
    return cell
}

如何获取当前单元格的重用标识符,以便我可以根据它是什么类型的单元格来更改高度?

4

1 回答 1

0

reuseIdentifier是 的一个属性UICollectionViewReusableView,它是UICollectionViewCell的基类。因此cell.reuseIdentifier,一旦您拥有一个单元格,您就可以随时调用。

我不确定您对“当前单元格”的概念是什么。您可以使用 查询索引路径中给定单元格的集合视图collectionView.cellForItemAtIndexPath(),并且您可以通过实现委托方法collectionView:didSelectItemAtIndexPath:然后保存当前选择的 indexPath 来跟踪当前选择了哪个单元格。

或者(我建议)是您要么子类UICollectionViewCell化并让子类化单元负责其自身的高度,要么实现自定义UICollectionViewLayout类并在那里处理大小。

如果您实现自己的单元格子类,请务必调用registerClass:forCellWithReuseIdentifier:您的自定义单元格,以便UICollectionView知道如何正确创建它。

于 2015-12-02T11:37:21.153 回答