【问题标题】:Hide button in CollectionViewCell after audioPlayerDidFinishPlaying在 audioPlayerDidFinishPlaying 之后隐藏 CollectionViewCell 中的按钮
【发布时间】:2018-09-15 07:11:09
【问题描述】:

我在 ViewController 中有一个 CollectionView。 此 collectionView 中的每个 collectionViewCell 都有一个按钮。按下按钮后,音频开始播放。 我想做的是在音频播放完毕后隐藏按钮。

如何在 audioPlayerDidFinishPlaying 委托方法中访问 c​​ollectionViewCell 中按钮的 isHidden 属性?

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, AVAudioPlayerDelegate {


func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    print("Did finish playing audio.")
}

【问题讨论】:

    标签: swift button uicollectionview uicollectionviewcell


    【解决方案1】:

    考虑到你的音频文件 url 是唯一的,那么你可以得到 player.url 然后找到这个 url 的索引,然后你可以得到 indexPath。

    例如

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    
            print(player.url ?? "play")
    
            if let playerFileName = player.url?.lastPathComponent, let index = urls.index(of: playerFileName), let cell = collectionView.cellForItem(at: IndexPath(row: index, section: 0)) as? AudioCollectionViewCell {
    
                cell.playButton.isHidden = true
            }
    
        }
    

    如果不是这种情况,则将当前的普通索引保存在某处,然后您可以在该索引处找到单元格并隐藏/取消隐藏按钮。

    【讨论】:

      【解决方案2】:

      您需要知道要隐藏按钮的单元格的indexPath。然后在您的 audioPlayerDidFinishPlaying 方法中执行以下操作:

      func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
          if let cell = collectionView.cellForItem(at: savedIndexPath) as? YourCustomCellClass {
              cell.button.isHidden = true
          }
      }
      

      或者如果你不想要可选的if let cell,你可以像这样强制展开:

      func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {    
          let cell = collectionView.cellForItem(at: savedIndexPath) as! YourCustomCellClass
          cell.button.isHidden = true
      }
      

      请注意,savedIndexPath 是您要隐藏按钮的单元格的 indexPath,YourCustomCellClass 是您正在使用的 UICollectionViewCell 的子类。

      【讨论】:

      • 如果您一次只允许播放一种声音,这将起作用。 (并且您可能需要逻辑来防止用户在当前播放声音时点击不同的播放按钮。)如果一次播放多个声音是有效的,您需要一种基于 indexPath 查找的方法声音播放器。我在想你可以创建一个 [AVAudioPlayer : IndexPath] 类型的字典来查找给定声音播放器的 IndexPath。
      猜你喜欢
      • 2022-01-10
      • 2011-09-04
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多