sizeForItemAtIndexPath 中的 UICollectionView reuseIdentifier - swift

UICollectionView reuseIdentifier in sizeForItemAtIndexPath - swift

我有以下代码,它根据屏幕大小将集合视图放入一列或两列中:

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
}

如何获取当前单元格的 reuseIndentifier,以便根据单元格类型更改高度?

reuseIdentifierUICollectionViewReusableView 的 属性,它是 UICollectionViewCell 的基础 class。因此,您可以在拥有单元格后随时调用 cell.reuseIdentifier

我不确定您对 "current cell" 的看法是什么。您可以使用 collectionView.cellForItemAtIndexPath() 向索引路径中的给定单元格询问集合视图,并且您可以通过实现委托方法 collectionView:didSelectItemAtIndexPath: 跟踪当前选择的单元格,然后保存当前选择的 indexPath。

或者(我建议的)是你要么 subclass UICollectionViewCell 并让 subclassed 单元格负责它自己的高度,或者实现一个自定义 UICollectionViewLayout class 并在那里处理大小。

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