Swift-如何从UITableViewCell中的按钮调用UIVIewController

Mar*_*zes 0 uitableview uiviewcontroller ios swift

我有一个UITableViewCell(.xib),在此单元格中有一个按钮,当按下按钮时,我想打开一个UIViewController

在此处输入图片说明

图标是我的按钮

在我的TableViewController

class DetalhaConsultaServidorViewController: UITableViewController {

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

    let cell = Bundle.main.loadNibNamed("HistoricoClienteServidorTableViewCell", owner: self, options: nil)?.first as! HistoricoClienteServidorTableViewCell

...
    return cell
}
Run Code Online (Sandbox Code Playgroud)

和我的CustomCell班级:

class HistoricoClienteServidorTableViewCell: UITableViewCell {

    @IBAction func actionButton(_ sender: Any) {

        //how open a UIViewController (xib or main.storyboard)?
    }
    ...
Run Code Online (Sandbox Code Playgroud)

如何打开UIViewController(xib或main.storyboard)?

谢谢!

Kar*_*raj 5

您可以delegate在此用例中使用模式,

您的tableViewCell

protocol HistoricoClienteServidorTableViewCellDelegate {
    func didButtonPressed()
}

class HistoricoClienteServidorTableViewCell: UITableViewCell {
    var delegate: HistoricoClienteServidorTableViewCellDelegate?

    @IBAction func actionButton(_ sender: Any) {
       delegate?.didButtonPressed()
    }
}
Run Code Online (Sandbox Code Playgroud)

您的ViewController

class DetalhaConsultaServidorViewController: UITableViewController {

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

    let cell = Bundle.main.loadNibNamed("HistoricoClienteServidorTableViewCell", owner: self, options: nil)?.first as! HistoricoClienteServidorTableViewCell

    cell.delegate = self
    return cell
}

extension DetalhaConsultaServidorViewController: HistoricoClienteServidorTableViewCellDelegate {

      func didButtonPressed() {
          // Push or present your view controller
      }

}
Run Code Online (Sandbox Code Playgroud)

谢谢。