首页 > 解决方案 > 更改随机选择的图像的 Alpha 设置

问题描述

和我昨晚问的类似的问题。但是我花了一天时间阅读和整理我的代码。我正在尝试使网格中的随机正方形将其 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
        }

    }
    '''

标签: arraysswiftrandomalphacollectionview

解决方案


答案是

cell.contentView.alpha = 0

非常感谢 Code Crew 社区的 Mark。

小心。


推荐阅读