swift - 如何仅选择带有按钮的点击单元格?

标签 swift tableview

一天中的好时光,在我的应用程序中,我有一个表格 View 和自定义单元格,在单元格中有标签、按钮和进度条,这样当我点击按钮下载时,进度条就会显示进度,但是当我向下滚动时,我意识到还有其他单元格被选中并显示进度,当我再次向上滚动时,所选单元格的进度停止。您能帮忙吗?任何反馈表示赞赏)

这是我的 TableViewController :

 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return titles.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell
        cell.pesnya.text = titles[indexPath.row]
        cell.pevets.text = artists[indexPath.row]
        cell.url = urls[indexPath.row]
    return (cell)
}

@IBAction func buttonPressed(_ sender: AnyObject) {
    (sender as! UIButton).isSelected = !(sender as! UIButton).isSelected
    if (sender as! UIButton).isSelected {
        if let indexPath = tableView.indexPath(for: sender.superview!?.superview as! UITableViewCell) {
            DownloadManager.shared.download(url: urls[indexPath.row], title: titles[indexPath.row])
        }
    } else {
        //            (sender as! UIButton).setTitle("Удалить", for: UIControlState.normal)
        if let indexPath = tableView.indexPath(for: sender.superview!?.superview as! UITableViewCell) {
            let name = "\(titles[indexPath.row]).mp3"
            let name2 = name.replacingOccurrences(of: " ", with: "")
            let filePathURL = URL(string:"string")
            do {
                try FileManager.default.removeItem(at: filePathURL!)
            } catch {
                print("Could not delete file: \(error)")
            }
        }
    }

}

最佳答案

这是因为滚动时 TableView 单元格将被重用。在单元格的 prepareForReuse 中将 View 设置为初始状态。像这样:

class ACell: UITableViewCell {
    override func prepareForReuse() {
        view.hidden = true
    }
}

关于swift - 如何仅选择带有按钮的点击单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45977900/

相关文章:

ios - Swift 数组没有正确维护项目

swift - 如何访问静态单元格

ios swift制作表列表不断收到关于nill的错误

ios - 更改 tableView 中偶数单元格的背景颜色

iOS:在其他 View 中嵌入表格 View (但表格 View 有一个复杂的表格 View Controller ..)

swift - 如何更改 UserDefaults 中的值的类型?

ios - addTarget 不触发任何事件

ios - UIView 没有动画的原因

swift - 迭代 firebase 的子项以查找与用户电话号码匹配的键

JavaFX 动态添加行和列到 TableView