从自定义单元重新加载tableview数据

Swi*_*ier 7 tableview custom-cell reloaddata swift

我有一个自定义单元格的tableView.

我还有一个针对这个custrom单元的.swift文件.

在这个文件中,我有一个函数,它没有发送者:AnyObject输入参数.

如何从此函数调用tableView.reloadData()?

Iam*_*hed 16

尝试创建一个委托.(我假设你知道,如果不看看有关委托和协议的苹果文档)

所以我建议的想法是创建一个将在UITableViewController(或符合UITableViewDelegate协议的UIViewController)中实现的函数

首先尝试在CustomCell.swift文件之上添加协议.

protocol CustomCellUpdater: class { // the name of the protocol you can put any
    func updateTableView()
} 
Run Code Online (Sandbox Code Playgroud)

然后在CustomCell.swift中:

weak var delegate: CustomCellUpdater?

func yourFunctionWhichDoesNotHaveASender () {
    ...
    delegate?.updateTableView()
}
Run Code Online (Sandbox Code Playgroud)

之后在你的UITableViewController(或同等的)

func updateTableView() {
    tableView.reloadData() // you do have an outlet of tableView I assume
}
Run Code Online (Sandbox Code Playgroud)

最后让你的UITableview类符合CustomCellUpdater协议

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

   let cell = tableView.dequeueReusableCell(withIdentifier: "yourIdentifier", for: indexPath) as! YourTableViewCell
   cell.delegate = self
}
Run Code Online (Sandbox Code Playgroud)

理论上它应该有效.如果我错过任何东西,请告诉我