如何使用每个collectionView单元的摇动手势播放声音?

时间:2016-12-01 13:02:36

标签: ios swift uicollectionview

我创建了一个collectionView,它可以水平滚动。我想要的是,例如当我在第一个单元格并摇动我的设备时,我想在阵列中播放第一个声音。当我在第二个文件并摇动我的设备时,我想在我的阵列中播放第二个文件。

我到目前为止:

var selectedIndex : Int = 0

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectedIndex = indexPath.row
    }

    override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?)
    {

       // var currentRow = self.collectionView.indexPath(for: self.collectionView.visibleCells[0])?.row

        if selectedIndex == 0 {
            do
            {
                audioPlayer1 = try AVAudioPlayer(contentsOf:Sound1!, fileTypeHint:nil)
            }
            catch
            {
                return print("file not found")
            }
            audioPlayer1.numberOfLoops = 0
            audioPlayer1.prepareToPlay()
            audioPlayer1.play()
        } else if selectedIndex == 1 {
            do
            {
                audioPlayer2 = try AVAudioPlayer(contentsOf:Sound2!, fileTypeHint:nil)
            }
            catch
            {
                return print("file not found")
            }
            audioPlayer2.numberOfLoops = 0
            audioPlayer2.prepareToPlay()
            audioPlayer2.play()

        }

2 个答案:

答案 0 :(得分:0)

创建一个var selectedIndex:Int

override func collectionView(collectionView: UICollectionView!, didSelectItemAtIndexPath indexPath: NSIndexPath!)
 {
   selectedIndex = indexPath.row
}

现在你可以使用selectedIndex访问你的数组并播放所选单元格的声音

答案 1 :(得分:0)

试过这个并且它有效!!

override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?)
    {

       let currentRow = self.collectionView.indexPath(for: self.collectionView.visibleCells[0])?.row

        if currentRow == 0 {

            do
            {
                audioPlayer1 = try AVAudioPlayer(contentsOf:Sound1!, fileTypeHint:nil)
            }
            catch
            {
                return print("file not found")
            }
            audioPlayer1.numberOfLoops = 0
            audioPlayer1.prepareToPlay()
            audioPlayer1.play()

        } else if currentRow == 1 {

            do
            {
                audioPlayer2 = try AVAudioPlayer(contentsOf:Sound2!, fileTypeHint:nil)
            }
            catch
            {
                return print("file not found")
            }
            audioPlayer2.numberOfLoops = 0
            audioPlayer2.prepareToPlay()
            audioPlayer2.play()

        }


        }