簡體   English   中英

在自定義UITableViewCell中單擊按鈕時重新加載UITableView

[英]Reload UITableView when button clicked in custom UITableViewCell

我的表格視圖單元格中有一個按鈕,我想重新加載整個視圖,這是基本控制器。

此類是我想要重新加載的類(刷新,也許重新調用視圖控制器)。

import UIKit 

class TableVC: BaseController, DBDelegate, PLDelegate {

@IBOutlet weak var tableViewDB: UITableView!

}

這是我必須執行的操作:

import UIKit

class DailySpeakingLesson: UITableViewCell {

}

為此使用委托

tableView(_:cellForRowAt:)設置自定義單元的委托,然后在委托的函數內調用tableViewDB.reloadData()

桌面VC

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

每日口語課

class DailySpeakingLesson: UITableViewCell {
    weak var delegate: DailySpeakingLessonDelegate?

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

代表

protocol DailySpeakingLessonDelegate: class {
    func dailySpeakingLessonButtonPressed()
}

最佳實踐是使用委托模式。 如果在DemoTableViewCell中有一個要在BaseTableViewController中使用的按鈕,請制定協議BaseTableViewCellDelegate並將BaseTableViewCell的委托分配給BaseTableViewController,以便通知基本ViewController在單元格中被按下。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM