ios - 如何使用swift在表格视图单元格中只单击一个按钮
问题描述
我有一个表格视图,每个单元格中都有按钮。每个按钮为每个单元格播放不同的歌曲并将图像更改为“播放”或“暂停”。但是我有一个问题,当我点击两个或三个按钮时,它们会将照片更改为“暂停”。它应该只在其中一个上更改照片。检查照片:单元格中的按钮
视图控制器中有我的代码:
extension BeatPackViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 12
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: CustomLoopsCell = beatTableView.dequeueReusableCell(withIdentifier: "firstLoopCell", for: indexPath) as! CustomLoopsCell
gettingSongName()
cell.loopNameLabel.text = data[indexPath.row].loop_name
cell.producerLabel.text = data[indexPath.row].producer
cell.instrumentLabel.text = data[indexPath.row].Instrument
cell.delegate = self
cell.selectionStyle = .none
cell.tag = indexPath.row
if let playingCell = currentPlayingIndex {
if playingCell == indexPath.row {
cell.playButtonOutlet.setImage(UIImage(named: "Pause.png"), for:
.normal)
}
} else {
cell.playButtonOutlet.setImage(UIImage(named: "playBtn.png"), for:
.normal)
}
// cell.instrumentLabel.text = data[indexPath.row].loops[indexPath.row].Instrument
// cell.producerLabel.text = data[indexPath.row].loops[indexPath.row].producer
return cell
}
func btnUseTap(cell: CustomLoopsCell) {
let indexPath = self.beatTableView.indexPath(for: cell)
if currentPlayingIndex == cell.tag {
audioPlayer.pause()
currentPlayingIndex = nil
beatTableView.reloadData()
} else { //IF PAUSE BUTTON
playLoop(song_name: songs[cell.tag])
currentPlayingIndex = cell.tag
beatTableView.reloadData()
}
beatTableView.reloadData()
// playSong(index: indexPath!.row)
print("Done")
}
解决方案
1)首先创建按钮的空数组,例如:
let allButtons: [UIButton] = []
2)当您创建每个单元格时,将该单元格的按钮添加到数组中,示例代码:
allButtons.append(yourButton)
3)创建将静音所有按钮并为它们分配暂停图像的功能,例如:
func muteAllButtons() {
for button in allButtons {
button.muteThisButton()
button.setImageToPlay()
}
}
创建将处理静音所有按钮的函数,然后从选定的按钮播放音乐,例如:
func userSelectedButton(at yourSelectedCellIndex: Int) { muteAllButtons() let currentPlayingButton = allButtons[yourSelectedCellIndex] currentPlayingButton.playMusic() currentPlayingButton.setImageToPause()
}
当用户单击选定的单元格时,调用 userSelected 函数。例如:
userSelectedButton(at: yourCellIndex)
推荐阅读
- android - 约束流量百分比无法正常工作
- python - 有没有办法从 TimeToGuess 类访问我的guesses_left 变量,以便我需要检查它们是否用完猜测
- r - R没有从CSV导入所有行
- django - 如何在 django 中将上下文变量放入模板标签 - 修改 Wagtail Menus 模板标签
- c# - 多个连接到同一 TransactionScope 中的同一 DB
- ios - 如何在 Swift 中为 OTP 倒计时
- ios - 更改 UIAlertViewController 色调颜色
- windows - windows azure vm 将端点暴露给互联网
- sql - 对 SQL Server 时态表中的时间使用选择查询
- r - 将时间戳与 lubridate 中的总时间结合起来