簡體   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