我创建了一个表格视图(Xcode 11,Swift 5),在其中放置了集合视图,还创建了一个图像数组:
let badgesImages: [UIImage] = [
UIImage(named: "Plastic Bottle Challenge bronze")!,
UIImage(named: "Plastic Bottle Challenge silver")!,
UIImage(named: "Plastic Bottle Challenge gold")!,
UIImage(named: "Car Challenge bronze")!,
UIImage(named: "Car Challenge silver")!,
UIImage(named: "Car Challenge gold")!,
]
在这里被召回:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.badgesImageView.image = badgesImages[indexPath.item]
return cell
}
我需要从阵列中选择三张图像来填充表格视图的一个单元格,并且需要为每个单元格重复该过程。我怎样才能做到这一点?预先感谢!
答案 0 :(得分:0)
import Foundation
let badgesImages = [
"Plastic Bottle Challenge bronze",
"Plastic Bottle Challenge silver",
"Plastic Bottle Challenge gold",
"Car Challenge bronze",
"Car Challenge silver",
"Car Challenge gold"
]
extension Array {
func pick(_ n: Int) -> [Element] {
guard count >= n else {
fatalError("The count has to be at least \(n)")
}
guard n >= 0 else {
fatalError("The number of elements to be picked must be positive")
}
let shuffledIndices = indices.shuffled().prefix(upTo: n)
return shuffledIndices.map {self[$0]}
}
}
badgesImages.pick(3)