简体   繁体   English

如何从UITableViewDataSource设置UITableViewCell的委托?

[英]How do I set the delegate of a UITableViewCell from a UITableViewDataSource?

In my UITableViewController I have set an external class for the DataSource. 在我的UITableViewController中,我为DataSource设置了一个外部类。 As below 如下

class HomeViewDataSource: NSObject, UITableViewDataSource {

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCellWithIdentifier(myCellIdentifier, forIndexPath: indexPath)
      cell.delegate = //Should I set this to the view controller?
      return cell
  }
}

As you can see, I have a reusable cell that I would like to set a delegate for. 如您所见,我有一个可重用的单元格,我想为其设置一个委托。 In the cell I have a button that triggers an event on the UITableViewController. 在单元格中,我有一个按钮触发UITableViewController上的事件。 For now, I have set the delegate of the cell to my UITableViewController so that it can perform a network call. 现在,我已经将单元格的委托设置为我的UITableViewController,以便它可以执行网络调用。 I do not believe I am doing this in a correct MVC format however. 我不相信我是以正确的MVC格式执行此操作。

The network call in the UITableViewController uses a property from an array in the UITableViewDataSource. UITableViewController中的网络调用使用UITableViewDataSource中的数组中的属性。

What is a better method to do this? 有什么更好的方法可以做到这一点?

I had another think about this and decided to try using a closure. 我对此有另一种想法,决定尝试使用闭包。 Here is how I could do it. 这是我的方法。

//MyCellClass: UITableViewCell

@IBAction func buttonPressed(sender:UIButton) {
  buttonNetworkCall?(self)
}

and in the UITableViewDataSource 并在UITableViewDataSource中

//HomeViewDataSource: NSObject, UITableViewDataSource {

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(myCellIdentifier, forIndexPath: indexPath)

    cell.buttonNetworkCall = { (cell) in
      self.makeButtonNetworkCall(cell)
    }

  return cell
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM