使用自定义单元格中的按钮并传递对象来执行 segue



我正在尝试为我的母亲编写一个平板电脑跟踪应用程序,但我遇到了一个问题,我正在使用编辑按钮访问静态表视图,但它拒绝传递药物对象。

我需要能够在 prepare(for:sender:) 中获取 indexPath,我通常会使用 tableView.indexPathForSelectedRow,然后使用该行从数组中提取正确的行,但由于我使用的是按钮,这是不可能的。

我尝试使用标签来存储行,我已经尝试了此处其他答案中建议的协议,但没有成功。当我尝试转到编辑屏幕时,该应用程序仍然崩溃。我在下面有我当前的代码,经历了太多的迭代,无法全部列出

@IBAction func editButtonTapped(_sender: UIButton) {
let point = sender.convert(CGPoint.zero to self.tableView)
buttonIndexPath = self.tableView.indexPathForRow(at: point)
preformSegue(withIdentifier: "showDetails", sender: sender)
}

我的准备(为:发件人:)代码如下

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetails" {
let destination = segue.destination as! MedicineDetailTableViewController
let selectedMedicine = medicines[(buttonIndexPath?.row)!]
destination.medicine = selectedMedicine
}
}

我很抱歉,如果这是我错过的愚蠢的东西,但我在智慧的尽头。

您可以使用以下功能为自定义单元格设置委托

func buttonTapped(_ sender: UITableViewCell)

然后,您可以使用sender在tableView上获取indexPath(for:)IndexPath并执行segue。

然后,您的tableView(_:cellForRowAt:)可能如下所示:

tableView(_:cellForRowAt:){
//setup other stuff and dequeue cell
cell.delegate = self
return cell
}

在这种情况下,我正在执行以下步骤:

1)将"您的编辑按钮"添加到您的UITableViewCell并创建IBOutlet。

class YourTableViewCell: UITableViewCell {
@IBOutlet weak var yourEditButton: UIButton!
}

2)cellForRowAtIndexPath方法中,将按钮标签分配为索引。

cell.yourEditButton.tag = indexPath.row

3)在视图控制器中创建 IBAction。打开情节提要并将"您的编辑按钮"与此 IBAction 函数连接。

class YourViewController: UIViewController {
let selectedMedicine: Medicine? //your global Medicine variable
@IBAction func editButtonTapped(_sender: UIButton) {
//now you can access selected row via sender.tag
selectedMedicine = medicines[sender.tag]
preformSegue(withIdentifier: "showDetails", sender: nil)
}
}

最后:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetails" {
let destination = segue.destination as! MedicineDetailTableViewController
destination.medicine = selectedMedicine
}
}

最新更新