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



我有一个带有自定义单元格的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类符合CustomCellUpdater协议

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: "yourIdentifier", for: indexPath) as! YourTableViewCell
   cell.delegate = self
}

理论上是可行的。如果我错过了什么,请告诉我

您可以使用委托和协议来完成此操作。

  1. 进入cell类并在上面添加此协议:

    protocol updateCustomCell: class { 
        func updateTableView() 
    }
    
  2. 将此变量添加到单元格类中:

    weak var delegate: updateCustomCell?
    
  3. 去你想要更新或访问变量的类,并在那里添加这个函数:

    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
        */
    }
    

不要忘记在类内部实现协议(非常重要)。

最新更新