在iOS中点击单元格附件时如何获取数据

时间:2019-03-04 14:13:53

标签: ios swift segue cell accessory

我有一个包含多个单元格的tableview,当用户点击该单元格时,它还具有其他功能,而当点击了单元格附件时,我希望它可以连接到另一个视图控制器 我能够这样做,但问题是我无法在单元格索引路径行发送数据,要发送数据,我首先必须触摸单元格,然后点击附件以发送数据,这是tableview的代码< / p>

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

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

感谢@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")
}

答案 2 :(得分:0)

只需在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]
   }
} 

答案 3 :(得分:0)

尝试一下,

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