swift - UICollectionView 在 sizeForItemAtIndexPath 中重用标识符 - swift

标签 swift uicollectionview reuseidentifier

我有以下代码,它将 Collection View 放入一列或两列中,具体取决于屏幕的大小:

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 的基类。因此,一旦拥有单元格,您就可以随时调用 cell.reuseIdentifier

我不确定你对“当前单元格”的概念是什么。您可以使用collectionView.cellForItemAtIndexPath()向 Collection View 询问索引路径处的给定单元格,并且可以通过实现委托(delegate)方法collectionView:didSelectItemAtIndexPath:<来跟踪当前选择的单元格 然后保存当前选择的indexPath。

或者(我建议)是您可以子类化 UICollectionViewCell 并让子类化的单元格负责其自己的高度,或者实现自定义 UICollectionViewLayout 类以及 handle 尺寸。

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

关于swift - UICollectionView 在 sizeForItemAtIndexPath 中重用标识符 - swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34040575/

相关文章:

ios - UITableViewCell 持有 UICollectionView 并点击集合单元格 segue

ios - UITableView 分隔符通过单元格重用错误绘制?

ios - 在真实设备中调用方法 'FirebaseApp.configure()'时,应用程序崩溃

ios - 以编程方式设置 Swift 元素的位置

ios - 快速制作数据网格的最佳方法是什么?

ios - 使用动态大小的单元格限制 UICollectionView 的数量

ios - 在 UITableView 内以编程方式将 UIView 添加到 UIStackView

ios - 引用具有重用标识符的单元格

swift AVAudioEngine 将多声道非交错信号转换为单声道

swift - 如何根据方案将两个不同的解析数据库链接到应用程序?