如何检测已选择不同的集合视图单元格?

How to detect that a different collection view cell has been selected?

我正在开发一个音乐应用程序,通过 selecting 集合视图单元格播放曲目 - 我希望单元格在 selected/tapped 首次 selected 时播放并且如果 selected/tapped 再次暂停。当 selected 相同的单元格时,我可以有效地播放和暂停,但是当我 select 不同的单元格时,问题就出现了。如何分离逻辑以便我可以发现一个新单元格已被 selected? (因此可以播放和暂停另一首曲目)。我已经尝试过 didSelectItemAt 委托方法,但是每次单元格被 selected 时都会调用它,我不知道如何检测不同的单元格是否被 selected。

换句话说,我正在寻找的行为是:单元格 1 被轻按 - 曲目 1 播放,单元格 1 被再次轻按 - 曲目 1 暂停 单元格 1 被轻按 - 曲目播放 1 次,点击单元格 2 - 曲目播放 2 次。

如有任何帮助,我们将不胜感激。

P.S。我正在使用 Swift

Visual representation of the App (a collection view where each cell is a seperate track)

编辑

var currentTrack: Int!

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {  

          currentTrack = indexPath.item

   switch selected {
    case true:
        playAudio()
    case false: 
    //Trying to match the current indexPath against the selected cell so I can play and pause that one
     if currentTrack != indexPath.item {
         playAudio()
      } else {
        pause()
      }
    } 
} 

 func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {

  pointerArray[keys[indexPath.item]] = false
  print("Stop", keys[indexPath.item])

}

您可以使用 indexPath 来检查正在选择的项目。我将以 print 为例,但您可以添加以相同方式播放的代码。

var songArray = ["SongOne", "SongTwo", "SongThree"]

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    print(songArray[indexPath.item])

}

编辑

在那种情况下,我会为每首歌曲设置一个字典和一个指针数组来检查当前曲目是否正在播放。还。如果你想在新曲目开始播放时停止当前曲目,你可以使用 didDeselectItemAt 函数。以下是同时使用函数和打印的代码作为示例:

var songKeys = ["SongOne", "SongTwo", "SongThree"]
var songArray = ["SongOne" : false, "SongTwo" : false, "SongThree" : false]

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {


    if songArray[songKeys[indexPath.item]] == false {
        songArray[songKeys[indexPath.item]] = true
        print("Playing", songKeys[indexPath.item])
        return
    }

    songArray[songKeys[indexPath.item]] = false
    print("Stop", songKeys[indexPath.item])

}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {

    songArray[songKeys[indexPath.item]] = false
    print("Stop", songKeys[indexPath.item])

}