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

时间:2018-05-17 14:29:12

标签: ios swift uitableview

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

我需要能够在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)
}

和我的prepare(for: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
    }
}

我道歉,如果这是一个愚蠢的事情,我错过了,但我已经结束了。

2 个答案:

答案 0 :(得分:1)

您可以使用

等功能为自定义单元格设置委托
func buttonTapped(_ sender: UITableViewCell)

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

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

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

}

答案 1 :(得分:1)

在这种情况下,我按照以下步骤操作:

1)添加您的编辑按钮'进入private void setTitleText(String Title) { toolbar = getView().findViewById(R.id.toolbar); ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar); ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(Title); } 并创建IBOutlet。

UITableViewCell

2)class YourTableViewCell: UITableViewCell { @IBOutlet weak var yourEditButton: UIButton! } 方法中,将按钮标记指定为索引。

cellForRowAtIndexPath

3)在View Controller中创建IBAction。打开故事板并连接"您的编辑按钮"有了这个IBAction功能。

 cell.yourEditButton.tag = indexPath.row

<强>最后:

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