在自定义UITableViewCell中单击按钮时重新加载UITableView

时间:2017-09-13 14:07:05

标签: ios swift uitableview

我的表视图单元格中有一个按钮,我想重新加载整个视图,这是一个基本控制器。

这个类是我想要重新加载的(刷新,可能会调用视图控制器)。

import UIKit 

class TableVC: BaseController, DBDelegate, PLDelegate {

@IBOutlet weak var tableViewDB: UITableView!

}

这是我必须这样做的地方:

import UIKit

class DailySpeakingLesson: UITableViewCell {

}

2 个答案:

答案 0 :(得分:2)

为此使用委托

tableView(_:cellForRowAt:)中设置自定义单元格的代理,然后在代理人的功能中调用tableViewDB.reloadData()

<强> TableVC

class TableVC: BaseController, DBDelegate, PLDelegate, DailySpeakingLessonDelegate {
    @IBOutlet weak var tableViewDB: UITableView!

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dailySpeakingLesson = tableView.dequeueReusableCell(withIdentifier: "cellId") as! DailySpeakingLesson
        dailySpeakingLesson.delegate = self

        return dailySpeakingLesson
    }

    func dailySpeakingLessonButtonPressed() {
        tableViewDB.reloadData()
    }
}

<强> DailySpeakingLesson

class DailySpeakingLesson: UITableViewCell {
    weak var delegate: DailySpeakingLessonDelegate?

    @IBAction func buttonPressed() {
        delegate?.dailySpeakingLessonButtonPressed()
    }
}

<强>代表

protocol DailySpeakingLessonDelegate: class {
    func dailySpeakingLessonButtonPressed()
}

答案 1 :(得分:0)

最佳做法是使用委托模式。如果您在BaseTableViewController中使用DemoTableViewCell中的按钮,则创建一个BaseTableViewCellDelegate协议,并将BaseTableViewCell的委托分配给BaseTableViewController,以便通知基本视图控制器在单元格中按下按钮。

protocol DemoTableViewCell Delegate: class {
  func didTapDemoButton(onCell: DemoTableViewCell)
}

class DemoTableViewCell: UITableViewCell {

  weak var delegate: DemoTableViewCellDelegate?

  @IBAction func demoButtonAction(_ sender: UIButton) {
    delegate?.didTapDemoButton(onCell: self)
  }
}

class BaseTableViewController: UITableViewController {

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: DemoTableViewCell), for: indexPath)
    cell.delegate = self
    return cell
  }

}

extension BaseTableViewController: DemoTableViewCellDelegate {
  func didTapDemoButton(onCell: DemoTableViewCell) {
    //Whenever the button in cell is pressed this delegate method gets called because we have set delegate of DemoTableViewCell as of the base view controller.
    //now you can do here whatever you want when button is pressed.

    tableView?.reloadData()
  }
}