我创建了一个表视图(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
}
我需要从数组中选择三张图片来填充表视图的一个单元格,并且我需要为每个单元格重复这个过程。我如何才能做到这一点?先谢谢你了!
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)