从自定义单元格重新加载表视图数据

Reloading tableview data from custom cell

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

我也有这个自定义单元格的 .swift 文件。

在这个文件中,我有一个函数在输入参数时没有 sender:AnyObject。

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

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

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

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

protocol CustomCellUpdater: class { // the name of the protocol you can put any
    func updateTableView()
} 

然后在你的 CustomCell.swift:

weak var delegate: CustomCellUpdater?

func yourFunctionWhichDoesNotHaveASender () {
    ...
    delegate?.updateTableView()
}

之后在您的 UITableViewController(或同等学历)

func updateTableView() {
    tableView.reloadData() // you do have an outlet of tableView I assume
}

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

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

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

理论上应该可以。如果我遗漏了什么,请告诉我

您可以使用委托和协议来执行此操作。

  1. 转到单元格 class 及以上添加此协议:

    protocol updateCustomCell: class { 
        func updateTableView() 
    }
    
  2. 在您的单元格中添加此变量 class:

    weak var delegate: updateCustomCell?
    
  3. 转到您要在那里更新或访问变量的 class 并在那里添加此函数:

    func updateTableView() {
    
       /* write what you want here  
          simply what this means is you are trying to say if something happed
          in the custom cell and you want to update something or even want to
          access something from the current class inside your customCell class
          use this function not the protocol function
        */
    
    }
    

不要忘记在 class 中实现协议(非常重要)。