CollectionView,两个按钮无法通信 - Swift 4

时间:2017-12-13 09:04:14

标签: swift xcode uibutton uicollectionview swift4

我有一个有两个按钮的collectionView。正在根据数组创建CollectionView,相应地重命名第一个按钮。但第二个按钮始终是一个分享按钮。

对于每个CollectionviewCell,对于分享按钮,我需要到达并读取重命名第一个按钮的当前标题(它有一个.mp3文件,其名称与项目中按钮的标题完全相同)。这样我就可以根据第一个按钮的标题分享那个mp3文件了。但我无法伸手去拿它。知道怎么解决这个问题吗?

我不能将按钮的插座丢给ViewController,因为它们是重复的内容。

第一个播放按钮:

@IBAction func buttonPlayTapped(_ sender: UIButton) {
    let musicFile = Bundle.main.path(forResource: sender.currentTitle!, ofType: "mp3")

    do{
        try soundPlay = AVAudioPlayer(contentsOf: URL (fileURLWithPath: musicFile!))
    }
    catch {
        print(error)
    }
    soundPlay.play()
}

分享按钮:

@IBAction func shareTapped(_ sender: Any) {
    // I need to access the main button's title for 'forResource' in order to share that exact mp3 file
    let activityItemTwo = URL.init(fileURLWithPath: Bundle.main.path(forResource: "", ofType: "mp3")!)

    let activityVC = UIActivityViewController(activityItems: [activityItemTwo],applicationActivities: nil)
    activityVC.popoverPresentationController?.sourceView = self.view

    self.present(activityVC, animated: true, completion: nil)
}

这就是我在加载CollectionViewCells时重命名我的第一个按钮的方法:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! myCell
    cell.myVoiceButton.setTitle(soundNames[indexPath.row], for: .normal)

    return cell
}

1 个答案:

答案 0 :(得分:0)

首先你需要设置

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! myCell
cell.myVoiceButton.setTitle(soundNames[indexPath.row], for: .normal)
cell.yourhareBtn.tag = indexPath.row
return cell
 }

现在用

替换您的分享抽头方法
 @IBAction func shareTapped(_ sender: Any) {
    //cast into  uibutton to access its property
    let button  = sender as? UIButton
    // safly access button
    guard let currentButton = button else {return}
    // get title
    let title = soundNames[currentButton.tag]
    let activityItemTwo = URL.init(fileURLWithPath: Bundle.main.path(forResource: "", ofType: "mp3")!)

    let activityVC = UIActivityViewController(activityItems: [activityItemTwo],applicationActivities: nil)
    activityVC.popoverPresentationController?.sourceView = self.view

    self.present(activityVC, animated: true, completion: nil)
}

但请记住,这只适用于您没有删除或添加数据的情况。因为获取视图或按标签按钮不是一个好主意。但它应该适合您。让我知道您是否有任何问题