如何在 Collection 视图中仅更改 1 个按钮的图像并使 Swift 中的所有其他按钮图像不同

How do I change the Image of only 1 button in Collection View and make all other button Images different in Swift

在我的 collection 视图中,我有带有播放按钮的歌曲。我想在选择时更改按钮的图像,并希望将之前选择的按钮图像恢复为默认图像。按钮数量未知,可能在 1 到 20 之间的任何地方。任何帮助将不胜感激。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    if collectionView == self.albumCollection {
    let cellA = collectionView.dequeueReusableCell(withReuseIdentifier: "album", for: indexPath) as! AlbumsCollectionViewCell
        
        cellA.albumImg.image = UIImage(named: albums[indexPath.row])
        cellA.albumLbl.text = albumLbl[indexPath.row]
        
        
    return cellA
    }
    else {
        let cellB = collectionView.dequeueReusableCell(withReuseIdentifier: "songs", for: indexPath) as! ForYouCollectionViewCell
        
        cellB.forImg.image = UIImage(named: songs[indexPath.row])

        cellB.forButton.tag = indexPath.row
        cellB.delegate = self
               return cellB
    }
    
}

这是我的 collection 视图单元格的代码

import UIKit
import AVFoundation


protocol SongDelegate: AnyObject {
func songBtnTapped(sender: UIButton!)
}

class ForYouCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var forImg: UIImageView!
@IBOutlet weak var forButton: UIButton!
weak var delegate: SongDelegate?

var isTapped = false
var player: AVPlayer?
var counts: Int = 0
//test

override func awakeFromNib() {
    super.awakeFromNib()
    NotificationCenter.default.addObserver(self,selector: #selector(songBtn(_:)),name: Notification.Name("playSong"),object: nil)

}



func conditions() {
    
    
    if isTapped == false {
        forButton.setImage(UIImage(named: "wPlay"), for: .normal)
        isTapped = true


    } else {
        forButton.setImage(UIImage(named: "wPause"), for: .normal)
        isTapped = false
    }
    

    
}

@IBAction func songBtn(_ sender: UIButton) {
    delegate?.songBtnTapped(sender: sender)
    forButton.setImage(UIImage(named: ("wPause")), for: .normal)

    print(sender.tag)
    counts = sender.tag
    if counts == sender.tag {
        print(counts)
        forButton.setImage(UIImage(named: "wPlay"), for: .normal)
    } else if counts != sender.tag {
        
        forButton.setImage(UIImage(named: "wPause"), for: .normal)
    }

   
}
}

在您的 collectionView ViewController 上有一个包含 songPlaying: Int 的变量?然后在您的 cellForItemAt 函数中,您可以检查 indexPath.row == songPlaying show play else show pause。单击按钮将 songPlaying 更改为该标签并重新加载您的 collectionView。我不确定你的条件 func 在哪里被使用,但这似乎没有必要,你应该在单元格上有一个 buttonImage 变量并将它设置在 cellForItemAt 中。