在 ios 中点击手机配件时如何获取数据

how to get data when cell accessory is tapped in ios

我有一个有多个单元格的表视图,当用户点击单元格时它会执行一些其他功能,当点击单元格附件时我希望它转到另一个视图控制器 我能够这样做,但问题是我无法在单元格索引路径行发送数据,为了发送数据我首先必须触摸单元格然后点击附件发送数据这里是表视图的代码

func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
    myTableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    switch segue.identifier {
    case "ShowDetail":
        if let ip = myTableView.indexPathForSelectedRow{
            if let svc = segue.destination as? DetailViewController{
                svc.selectedObject = (myCounters?[ip.row])!
            }
        }
    default:
        print("error in segue")
    }
}
func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "detailvc") as? DetailViewController
vc?.selectedObject = (myCounters?[indexPath.row])!
navigationController?.present(vc!, animated: true, completion: nil)
}

感谢@shahzaib qureshi 我删除了 segue 连接并使用实例化视图控制器方法作为单元格附件点击方法中的详细视图控制器

func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "detailvc") as? DetailViewController
    vc?.selectedObject = (myCounters?[indexPath.row])!
    navigationController?.present(vc!, animated: true, completion: nil)
    print("ewwewew")
}

只需在sender参数中传递索引路径即可,非常简单:

func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { 
    performSegue(withIdentifier: "ShowDetail", sender: indexPath) 
} 

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
   if segue.identifier == "ShowDetail" { 
       let indexPath = sender as! IndexPath
       let svc = segue.destination as! DetailViewController
       svc.selectedObject = myCounters![indexPath.row]
   }
} 

试试这个,

func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
        print("Index : \(indexPath.row)")

    var tempIndex: Int!
    var tempIdentifier: String!

    self.tempIndex = indexPath.row //You can store indexpath.row value in temp variable. And then then you can access it while performing any other functions.
    self.tempIdentifier = "ShowDetail" //This upto your needs.
}

//UIStoryboardSegue 相应地移动到另一个控制器。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    switch segue.identifier {
    case "ShowDetail":
        if let ip = myTableView.indexPathForSelectedRow{
            if let svc = segue.destination as? DetailViewController{
                svc.selectedObject = (myCounters?[tempIndex])!
            }
        }
    default:
        print("error in segue")
    }
}