1 个部分中带有随机重用标识符的 UICollectionView

UICollectionView with randomized reuseIdentifiers in 1 section

我有一个包含 16 个单元格的 UICollectionView。 1 个单元格(游戏结束单元格)必须是随机的。我想在集合视图中随机化 Game Over 单元格。

我通过使用不同的部分让它有点工作,但这违背了在视觉上与 16 融合的目的。

我还通过创建一个字符串数组使它有点工作,其中一个字符串是 "GameOver" - 然后我对该数组进行了随机播放以自定义此单元格的显示方式。

那也没有用,因为它没有让我通过 IB 控制游戏。

我如何通过创建 2 个原型单元标识符来使用故事板,随机化游戏中的 1 个单元格,以及 16 个单元格的集合视图中的 15 个普通单元格?

这是一种相当简单的方法:

在您的视图控制器中,定义一个 属性 来保存以后可以引用的任何单元格重用标识符数组。您可以设置初始的非随机配置,如下所示:

var reuseIdentifiers = ["GameOver", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal"]

定义以下方法,并在视图控制器初始化期间调用它,在屏幕上显示 collectionView 之前,以及每次重新加载集合视图数据之前:

func randomizeReuseIdentifiers() {
    var randomized = [String]()

    for _ in initialIdentifiers {
        let random = reuseIdentifiers.removeAtIndex(Int(arc4random_uniform(UInt32(reuseIdentifiers.count))))
        randomized.append(random)
    }

    reuseIdentifiers = randomized
}

然后在您的 collectionView(cellForItemAtIndexPath:NSIndexPath) 方法中,查找当前 indexPath 的匹配 reuseIdentifier,如下所示:

func collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let identifier = reuseIdentifiers[indexPath.item]
    return collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath)
}

这种方法的另一个好处是允许您在将来向初始 reuseIdentifiers 数组添加额外的标识符,以在一个或多个随机位置包含其他类型的单元格。