【问题标题】:How to fix this collection view and arrays issue?如何解决此集合视图和数组问题?
【发布时间】:2016-10-18 09:32:30
【问题描述】:

我正在使用 Swift 3。我设置了一个包含 7 个部分的 collectionView - 当用户点击一个单元格(按钮)时,将从一组声音中播放特定的声音。

那么我如何拆分 collectionView 中的部分以匹配特定的声音数组?

例如

1) soundArray1 中的声音将在用户点击 collectionView 部分 1 中的单元格(按钮)时播放

2) soundArray2 中的声音将在用户点击 collectionView 部分 2 中的单元格(按钮)时播放

3) soundArray3 中的声音将在用户点击collectionView 第3 部分中的单元格(按钮)时播放

一直到第 7 节。

这是用户点击 cellButton 时的当前代码

@IBAction func cellButton(_ sender: AnyObject) {
let sound =  (sender as! UIButton).tag
self.setupAudioPlayer(file: Sounds[sound] as NSString, type: ".m4a")
self.soundPlayer.play()}

其中 Sounds 是声音文件的数组 1。然而,这组声音文件现在正在collectionView 的所有部分播放。我不知道如何拆分每个声音数组以匹配collectionView 中的每个部分。

【问题讨论】:

  • 使用声音数组的 Array 并使用节号提取正确的声音数组和单元格编号以从该数组中获取正确的声音?
  • 另外你是如何设置 UIButton 的标签的?

标签: ios arrays swift uicollectionview


【解决方案1】:

你需要为你的声音设置一个数组:

let allSounds = [soundArray1, soundArray2, soundArray3]

数组中的每个元素代表 collectionView 的部分。

要获得第 0 部分中第一个元素的声音,您可以:

let soundArray = allSounds[0]  // Get section 0
let sound = soundArray[0] // Get sound at index 0

或者要在第 2 部分的索引 7 处获得声音,您可以:

let soundArray = allSounds[2]  // Get section 2
let sound = soundArray[6] // Get sound at index 7

【讨论】:

  • 他的按钮标签必须同时代表 indexPath.section 和 indexPath.row
  • 假设每个部分的按钮数量相同,使用整数数学计算会相当容易:tag % no-of-items-in-section & tag / no-of-items-in-section
  • 但是,更好的方法是使用didSelectCellAtIndexPath 代替按钮,或者在单元格内阻塞以回调到控制器
  • 天台,这只是个假设。这就是为什么我们有 cmets 要求 OP 进行澄清。这个答案与我想到的方法几乎相同(请参阅我之前对问题的评论),但我需要澄清,所以我留下了评论。 (不暗示你做错了什么,西部最快的枪获胜;))
  • 是的,使用 tablview 代理更好,但同样,我们不知道他在单元格中是否有多个按钮或其他控件来执行不同的操作,因此 didSelectCell 对他来说可能不是一个有效的选择。所以,是的,再次发表评论。这只是帮助您了解 SO 的工作原理,因为您似乎是一个新用户。欢迎登机 :)
猜你喜欢
  • 1970-01-01
  • 2020-02-27
  • 2017-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多