【问题标题】:Swift - How to detect an action button in UItableViewCell is pressed from ViewController? [duplicate]Swift - 如何检测从 ViewController 按下 UItableViewCell 中的操作按钮? [复制]
【发布时间】:2018-05-08 18:18:39
【问题描述】:

我在 UITableViewCell 中有一个操作按钮,我想检测按钮何时被按下以及 ViewController 中按下的单元格的编号,以便在 ViewController.swift 中制作音频播放列表。

我已经被这个问题困扰了一段时间,我真的很感谢你的建议。这是代码。

ViewController.swift

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

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]***

    }

}

【问题讨论】:

  • 寻找代表。
  • 您能说得更具体些吗?谢谢。

标签: ios swift uitableview


【解决方案1】:

你可以选择一个很好的老式委托模式。这具有不将视图控制器与单元耦合的优点。不要忘记让您的代表weak 以避免保留周期。

您可以从表格视图中找到单元格索引路径。 (我假设单元格编号是指索引路径)

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
    }
}

【讨论】:

  • 您对didTap 的实现很奇怪。只需:let indexPath = self.tableView.indexPath(for: cell)。无需扫描可见细胞。
【解决方案2】:

在你的 ViewConroller 中试试这个

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

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

        //add tag to cell button to that of cell index
        cell.button.tag = indexPath.row

         //Observer for button click event inside cell
         cell.button.addTarget(self, action: #selector(pressButton(_:)), for: .touchUpInside)

        return cell

    }

//Mark: Button Action

@objc func pressButton(_ button: UIButton) {
    print("Button with tag: \(button.tag) clicked in cell!")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    相关资源
    最近更新 更多