我有一个包含 16 个单元格的 UICollectionView。 1 个单元格(游戏结束单元格)必须是随机的。我想在 Collection View 中随机化 Game Over 单元格。
我通过使用不同的部分让它有点工作,但这违背了在视觉上与 16 融合的目的。
我还通过创建一个字符串数组使它有点工作,其中一个字符串是“GameOver”——然后我对该数组进行了随机播放以自定义此单元格的显示方式。
那也没有用,因为它没有让我通过 IB 控制游戏。
我如何通过创建 2 个原型(prototype)单元格标识符来使用 Storyboard,随机化 1 个游戏结束单元格,以及 16 个单元格的 Collection View 中的 15 个普通单元格?
最佳答案
这是一种相当简单的方法:
在您的 View Controller 中,定义一个属性来保存以后可以引用的任何单元格重用标识符数组。您可以设置一个初始的、非随机的配置,如下所示:
var reuseIdentifiers = ["GameOver", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal"]
定义以下方法,并在 View Controller 初始化期间调用它,在屏幕上显示 collectionView 之前,以及每次重新加载 Collection View 数据之前:
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
数组添加额外的标识符,以在一个或多个随机位置包含其他类型的单元格。
关于ios - 1 个部分中带有随机重用标识符的 UICollectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36800860/