ios - Swift - 如何检测从 ViewController 按下 UItableViewCell 中的操作按钮?

标签 ios swift uitableview

<分区>

我在 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

    }


}

细胞.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]***

    }

}

最佳答案

您可以选择一个很好的老式委托(delegate)模式。这样做的好处是不会将您的 View Controller 与您的单元耦合。不要忘记让您的委托(delegate)弱化以避免保留周期。

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

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

关于ios - Swift - 如何检测从 ViewController 按下 UItableViewCell 中的操作按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47478257/

相关文章:

ios - iOS 5 中的自定义单元格问题

ios - Xcode 缺少支持文件 iOS 12.2 (16E227)

应用程序启动崩溃的 iOS BugSense 堆栈跟踪

ios - 无法更新/修改 SwiftUI View 的 @state var

ios - 快速将 UITableView 添加到 View Controller

ios - 隐藏或移动选定的 Cell 并在 UItableView 的 indexPath.row 中加载一个新的自定义 Cell

ios - 使用用户 NSContacts 查找 friend 页面非常慢 + "This application is modifying the autolayout engine from a background thread"

iphone - 如何将 UItextfield 属性分配给另一个 UItextfield

ios - 使 UIView 与 UITableView 一起滚动,但固定到顶部不可见

ios - SceneKit:在运行时从模型创建 SCNNode