从重用的自定义单元格中的按钮传递数据

2024-03-12

当用户点击自定义单元格中的按钮时,我无法从自定义单元格传递数据。由于单元格被重复使用,我有时会得到错误的单元格数据。我想知道是否有一种完整的方法可以始终将正确的单元格数据获取到每个单元格中的按钮,无论当前屏幕上的哪个单元格。下面是我的代码。任何帮助是极大的赞赏。

我的自定义单元格:

protocol CustomCellDelegate {
  func segueWithCellData()
}

class CustomTableViewCell : UITableViewCell {
  var delegate = CustomCellDelegate?

  @IBAction func buttonTapped() {
    if let delegate = self.delegate {
        delegate.segueWithCellData()
     }
   }
}

我的表视图控制器:

class MyTableViewController : UITableViewController, CustomCellDelegate {
   var posts = [Post]()
   var title: String!

   override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      let post = posts[indexPath.row]
      let cell =  tableView.dequeueReusableCellWithIdentifier("CustomCellReuseIdentifier", forIndexPath: indexPath)
      title = post.title

    cell.delegate = self        

    return cell
}

   func segueWithCellData() {
     self.performSegueWithIdentifier("passMyData", sender: self)
   }

   override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     if segue.identifier == “passMyData” {
        let destination = segue.destinationViewController as! UINavigationController
        let targetVC = destination.topViewController as! nextVC
        targetVC.title = title    
      }

    }
 }

我的自定义单元格:

protocol CustomCellDelegate {
  func segueWithCellData(cell:CustomTableViewCell)
}

class CustomTableViewCell : UITableViewCell {
  var delegate = CustomCellDelegate?

  @IBAction func buttonTapped() {
    if let delegate = self.delegate {
        delegate.segueWithCellData(self)
     }
   }
}

CustomCells 委托方法:

func segueWithCellData(cell:CustomTableViewCell) {
    //Get indexpath of selected cell here
    let indexPath = self.tableView.indexPathForCell(cell)
    self.performSegueWithIdentifier("passMyData", sender: self)
}

因此,不需要标记单元格。 由于您有所选单元格的索引路径,因此您可以从中获取数据并将其传递给sender的参数performSegueWithIdentifier method.

例如,

func segueWithCellData(cell:CustomTableViewCell) {
    //Get index-path of selected cell here
    let selectedIndexPath = self.tableView.indexPathForCell(cell)
    let post = posts[selectedIndexPath.row]

    self.performSegueWithIdentifier("passMyData", sender: post)
}

并且,获取里面的数据prepareForSegue如下:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     if segue.identifier == “passMyData” {
        let destination = segue.destinationViewController as! UINavigationController
        let targetVC = destination.topViewController as! nextVC

        //Get passed data here
        let passedPost = sender as! Post

        targetVC.title = title    
      }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从重用的自定义单元格中的按钮传递数据 的相关文章

随机推荐