gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:04:35 24 4
gpt4 key购买 nike

我在通过用户点击自定义单元格中的按钮从自定义单元格传递数据时遇到问题。由于单元格被重复使用,我有时会得到错误的单元格数据。我想知道是否有一种完整的证明方法可以始终将正确的单元格数据发送到每个单元格中的按钮,无论屏幕上当前是哪个单元格。下面是我的代码。非常感谢任何帮助。

我的自定义单元格:

protocol CustomCellDelegate {
func segueWithCellData()
}

class CustomTableViewCell : UITableViewCell {
var delegate = CustomCellDelegate?

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

MyTableViewController:

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

CustomCellDelegate 方法:

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

因此,不需要标记单元格。由于您拥有所选单元格的 indexPath,因此您可以从中获取数据并将其传递给 performSegueWithIdentifier 方法的 sender 参数。

例如,

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

关于ios - 从重复使用的自定义单元格中的按钮传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39306613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com