I have a button in my table view cell and I want to reload the whole view, which is a base controller.
This class is what I want to reload (refresh, recall the view controller maybe).
import UIKit
class TableVC: BaseController, DBDelegate, PLDelegate {
@IBOutlet weak var tableViewDB: UITableView!
}
And this is where I must do it:
import UIKit
class DailySpeakingLesson: UITableViewCell {
}
Use a delegate for this.
Set the delegate for the custom cell in tableView(_:cellForRowAt:)
, then call tableViewDB.reloadData()
inside the delegate's function.
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()
}
}
Delegate
protocol DailySpeakingLessonDelegate: class {
func dailySpeakingLessonButtonPressed()
}
The best practice is to use delegate pattern. If you have a button in DemoTableViewCell which you are using in BaseTableViewController make a protocol BaseTableViewCellDelegate and assign delegate of BaseTableViewCell to BaseTableViewController so that base viewcontroller is notified button is pressed in the cell.
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()
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.