【问题标题】:How do I set the delegate of a UITableViewCell from a UITableViewDataSource?如何从 UITableViewDataSource 设置 UITableViewCell 的委托?
【发布时间】:2016-10-19 00:52:09
【问题描述】:

在我的 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 中数组的属性。

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

【问题讨论】:

    标签: ios swift uitableview delegates datasource


    【解决方案1】:

    我又考虑了这一点,并决定尝试使用闭包。 这是我可以做到的。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-06
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多