gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:56:10 25 4
gpt4 key购买 nike

我有一个有两个按钮的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
}

最佳答案

首先你需要设置

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)
}

但请记住,这仅在您不删除或添加数据时才有效。因为通过标签获取 View 或按钮不是一个好主意。但它应该对您有用。如果您有任何问题,请告诉我

关于swift - CollectionView,两个按钮无法通信 - Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47789141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com