HTML5   发布时间:2022-04-27  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – Swift – 如何从ViewController中按下UItableViewCell中的动作按钮?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_450_2@
参见英文答案 > Issue Detecting Button cellForRowAt                                    3个
>             swift: how to get the indexpath.row when a button in a cell is tapped?                                    14个
我在UITableViewCell中有一个操作按钮,我想检测按钮的按下时间以及ViewController中按下的单元格编号,以便在ViewController.swift中创建音频播放列表.

我已经陷入这个问题一段时间了,我真的很赞赏你的建议.这是代码.@H_801_9@

ViewController.swift@H_801_9@

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDatasource {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.datasource = self

        tableView.register(UINib(nibName: "Cell",bundle: nil),forCellReusEIDentifier: "cell")

    }

    func tableView(_ tableView: UITableView,numberOfRowsInSection section: int) -> Int {
        return 3
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! Cell
        return cell

    }


}

Cell.swift@H_801_9@

import UIKit

class Cell: UITableViewCell {

    @IBOutlet weak var button: UIButton!

    @IBACtion func buttonPressed(_ sender: Any) {

        ***[Code to send the pressed cell's number to ViewController]***

    }

}
@H_450_2@

解决方法

你可以选择一个老式的代表模式.这样做的好处是不会将视图控制器与单元格耦合.不要忘记让你的代表弱,以避免保留周期.

您可以从表视图中找到单元索引路径. (我假设按单元格编号表示索引路径)@H_801_9@

protocol CellDelegate: class {
    func didTap(_ cell: Cell)
}

class Cell: UITableViewCell {

    weak var delegate: CellDelegate?
    @IBACtion func buttonPressed(_ sender: Any) {
        delegate?.didTap(self)
    }
}

class ViewController: UIViewController,CellDelegate {

    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = ...
        cell.delegate = self
        return cell
    }

    func didTap(_ cell: Cell) {
        let indexPath = self.tableView.indexPath(for: cell)
        // do something with the index path
    }
}
@H_450_2@ @H_450_2@
@H_450_2@
@H_450_2@

大佬总结

以上是大佬教程为你收集整理的ios – Swift – 如何从ViewController中按下UItableViewCell中的动作按钮?全部内容,希望文章能够帮你解决ios – Swift – 如何从ViewController中按下UItableViewCell中的动作按钮?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。