首页 > 解决方案 > Swift TableView 单元格播放按钮单击和其他单元格按钮需要重置

问题描述

我正在尝试使用 custom列出audio文件。在这里,每个单元格都有一个(用于音频)。我的问题是,如果我单击第一个单元格中的播放按钮或其他单元格选择按钮需要的任何单元格(我的意思是第一个单元格按钮单击其他或先前选择的需要暂停正常)。TableViewcellbuttonplay/pauseresetplaypausecell

我的当前输出屏幕

播放列表

下面我正在使用的代码,提供一些想法

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: InviteCell = inviteTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomOneCell

    // here some code missing
    cell.btnCheck.tag = indexPath.row
    cell.btnCheck.addTarget(self, action: #selector(self.btnCheck(_:)), for: .touchUpInside)

return cell
}

@objc func btnCheck(_ sender: UIButton) {

        // Here I need to change Image and how to Implement my question
        let cell = tableView.cellForRow(at: NSIndexPath(row: sender.tag, section: 0) as IndexPath) as! CustomOneCell

        /*if selectIndex != -1 && selectIndex != sender.tag
        {
            let bt:UIButton = self.view.viewWithTag(selectIndex) as! UIButton
            if bt.isSelected == true
            {
                bt.isSelected = false
                cell.playButton.setImage(UIImage(named:"play.png"), for: UIControlState.normal)
            }
        }*/

        if sender.isSelected == false
        {
            sender.isSelected = true
            selectIndex = sender.tag
            cell.playButton.setImage(UIImage(named:"pause.png"), for: UIControlState.normal)

        } else {
            sender.isSelected = false
            selectIndex = sender.tag
            cell.playButton.setImage(UIImage(named:"play.png"), for: UIControlState.normal)

        }
        self.tableView.reloadData()
}

标签: iosswifttableview

解决方案


我想在你的视图控制器的某个地方你有一系列的项目。这个项目应该有一些属性来表示项目是否正在播放。例如

var isPlaying: Bool = // true if playing, false if not

如果您只有字符串数组,则必须创建自定义类/结构

struct Audio {
    var title: String = ""
    var isPlaying: Bool = false
}

现在在

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: InviteCell = inviteTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomOneCell

    let item = yourItemArray[indexPath.row]
    let image = item.isPlaying ? UIImage(named:"pause.png") : UIImage(named:"play.png")
    cell.playButton.setImage(image, for: UIControlState.normal)
    cell.btnCheck.tag = indexPath.row
    cell.btnCheck.addTarget(self, action: #selector(self.btnCheck(_:)), for: .touchUpInside)

    return cell
}

在您的按钮的操作中,只需更改索引相同的项目的值

@objc func btnCheck(_ sender: UIButton) {
    for item in yourItemArray {
        item.isPlaying = false
    }
    yourItemArray[sender.tag].isPlaying = !yourItemArray[sender.tag].isPlaying
    self.tableView.reloadData()
}

推荐阅读