【发布时间】:2020-04-15 21:24:39
【问题描述】:
与我昨晚问的问题类似。但是我花了一天时间阅读和整理我的代码。我正在尝试使网格中的随机正方形将其 alpha 设置更改为 0。代码运行但所有正方形都按应有的方式显示,它们都不会变得透明。请帮忙!
只是为了让您知道,当我打印出随机元素时,输出框中的内容是 - UIImage:0x600000d0c7e0 named(main: gridsquare3) {120, 170}
谢谢
'''
let cellImages: [UIImage] = [UIImage(named: "gridsquare")!,UIImage(named: "gridsquare2")!,
UIImage(named: "gridsquare3")!,
UIImage(named: "gridsquare4")!,UIImage(named: "gridsquare5")!,UIImage(named: "gridsquare6")!,UIImage(named: "gridsquare7")!,UIImage(named: "gridsquare8")!,
UIImage(named: "gridsquare9")!,]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
//Timer creation
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerElapsed), userInfo: nil, repeats: true)
// Do any additional setup after loading the view.
}
//Mark: - Timer methods
@objc func timerElapsed() {
seconds -= 1
timerLabel.text = "\(seconds)"
if seconds <= 0 {
timer?.invalidate()}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cellImages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! CollectionViewCell
cell.yellowSquare.image = cellImages[indexPath.item]
let randomcell = cellImages.randomElement()
print(randomcell!)
if randomcell == UIImage(named: "gridsquare") {
cell.alpha = 0
}
else if randomcell == UIImage(named: "gridsquare2") {
cell.alpha = 0 }
else if randomcell == UIImage(named: "gridsquare3") {
cell.alpha = 0 }
else if randomcell == UIImage(named: "gridsquare4") {
cell.alpha = 0 }
else if randomcell == UIImage(named: "gridsquare5") {
cell.alpha = 0 }
else if randomcell == UIImage(named: "gridsquare6") {
cell.alpha = 0 }
else if randomcell == UIImage(named: "gridsquare7") {
cell.alpha = 0 }
else if randomcell == UIImage(named: "gridsquare8") {
cell.alpha = 0 }
else if randomcell == UIImage(named: "gridsquare9") {
cell.alpha = 0 }
else {
print("failure")
}
return cell
}
}
'''
【问题讨论】:
-
cellForRow被多次调用。在您的情况下,每行一次。如果你每行计算一个新的随机元素,它就行不通了。 -
@nighttalker 出于挫败感添加了“else if”语句,看看我是否可以让任何单元格变得透明。真的,我只想从集合视图中随机一个单元格将其 alpha 更改为 0。
-
@AugustoDiasNoronh 这更近了吗?
标签: arrays swift random alpha collectionview