首页 > 解决方案 > 按下按钮时,如何将表格视图中单元格的索引从一个视图控制器传递到下一个视图控制器?

问题描述

每次我尝试执行以下操作时,它将索引传递给下一个视图控制器为 0。我不确定我做错了什么,有人可以帮忙吗?非常感谢!以下是相关代码:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "a", for: indexPath) as! TableViewCell


    cell.useButton.tag = tagBaseValue + indexPath.row
    cell.useButton.addTarget(self, action: #selector(ListViewController.useButtonPressed(_:)), for: UIControlEvents.touchUpInside)

    return cell
}

@IBAction func useButtonPressed(_ sender: Any) {
    performSegue(withIdentifier: "toDisplay", sender: self)
}

func prepare(for segue: UIStoryboardSegue, sender: UIButton) {
    if segue.identifier == "toDisplay" {

        let nextVC = segue.destination as! NextVC

        nextVC.index = sender.tag

    }
}

标签: swiftuitableviewuibutton

解决方案


prepare(for永远不会因为签名错误而被调用(类型senderis Any?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toDisplay" {

        let nextVC = segue.destination as! NextVC
        nextVC.index = (sender as! UIButton).tag

    }
}

并且IBAction必须是

@IBAction func useButtonPressed(_ sender: UIButton) {
    performSegue(withIdentifier: "toDisplay", sender: sender)
}

推荐阅读