繁体   English   中英

如何从UITableViewDataSource设置UITableViewCell的委托?

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

在我的UITableViewController中,我为DataSource设置了一个外部类。 如下

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

如您所见,我有一个可重用的单元格,我想为其设置一个委托。 在单元格中,我有一个按钮触发UITableViewController上的事件。 现在,我已经将单元格的委托设置为我的UITableViewController,以便它可以执行网络调用。 我不相信我是以正确的MVC格式执行此操作。

UITableViewController中的网络调用使用UITableViewDataSource中的数组中的属性。

有什么更好的方法可以做到这一点?

我对此有另一种想法,决定尝试使用闭包。 这是我的方法。

//MyCellClass: UITableViewCell

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

并在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