【发布时间】:2016-10-14 16:38:07
【问题描述】:
使用 Swift 3
我设置了一个包含 7 个部分的 collectionView - 当用户点击一个单元格(按钮)时,将从一组声音中播放特定的声音。
那么我如何拆分 collectionView 中的部分以匹配特定的声音数组?
例如
1) soundArray1 中的声音将在用户点击 collectionView 部分 1 中的单元格(按钮)时播放
2) soundArray2 中的声音将在用户点击 collectionView 部分 2 中的单元格(按钮)时播放
3) soundArray3 中的声音将在用户点击collectionView 第3 部分中的单元格(按钮)时播放
一直到第 7 节。
这是用户点击 cellButton 时的当前代码
func numberOfSections(in collectionView: UICollectionView) -> Int {
return sections.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return self.appleProducts.count
} else if section == 1 {
return self.animals.count
} else if section == 2 {
return self.food.count
} else if section == 3 {
return self.activity.count
} else if section == 4 {
return self.travel.count
} else if section == 5 {
return self.objects.count
} else if section == 6 {
return self.symbols.count
} else {
return 0
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
if indexPath.section == 0 {
cell.cellButton.setTitle(appleProducts[indexPath.row], for: UIControlState.normal)
} else if indexPath.section == 1 {
cell.cellButton.setTitle(animals[indexPath.row], for: UIControlState.normal)
} else if indexPath.section == 2 {
cell.cellButton.setTitle(food[indexPath.row], for: UIControlState.normal)
} else if indexPath.section == 3 {
cell.cellButton.setTitle(activity[indexPath.row], for: UIControlState.normal)
} else if indexPath.section == 4 {
cell.cellButton.setTitle(travel[indexPath.row], for: UIControlState.normal)
} else if indexPath.section == 5 {
cell.cellButton.setTitle(objects[indexPath.row], for: UIControlState.normal)
} else if indexPath.section == 6 {
cell.cellButton.setTitle(symbols[indexPath.row], for: UIControlState.normal)
}
cell.cellButton.tag = indexPath.row
return cell
}
@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 中的每个部分
【问题讨论】:
-
使用
indexPathForItem(at point: CGPoint) -> IndexPath?(使用按钮的centre作为点)然后使用indexPath.section来确定从哪个数组中选择(使用indexPath.row)。 -
好像没有函数indexPathForItem?最接近的是 didSelectItemAt indexPath
-
见here。
-
谢谢您-您能否提供更多详细信息-例如 indexpathforitem 是独立功能还是在我的单元格按钮操作代码中?我的意思是在哪里放置这些功能的最佳位置?