Swift 使用PrepareForSequedRow时,indexPathForSelectedRow错误

Swift 使用PrepareForSequedRow时,indexPathForSelectedRow错误,swift,uitableview,didselectrowatindexpath,Swift,Uitableview,Didselectrowatindexpath,我试图用MySQL数据库中的一些产品(使用PHP POST文件)填充tableView,目前一切正常,但当我选择一个“单元格”时,PrepareForSequeue被触发,但indexPathForSelectedRow是错误的,因此它显示的是另一个产品 这是我的全部代码,我希望你能告诉我一些事情,因为我不知道为什么会发生这种情况,我已经尝试了很多事情,我没有选择了 TableViewController.swift import UIKit class ListadoBuscarResult

我试图用MySQL数据库中的一些产品(使用PHP POST文件)填充tableView,目前一切正常,但当我选择一个“单元格”时,PrepareForSequeue被触发,但indexPathForSelectedRow是错误的,因此它显示的是另一个产品

这是我的全部代码,我希望你能告诉我一些事情,因为我不知道为什么会发生这种情况,我已经尝试了很多事情,我没有选择了

TableViewController.swift

import UIKit

class ListadoBuscarResultadosTableViewController: UITableViewController {

var option: String = ""

var productos = [Producto]()

var refreshControl2:UIRefreshControl!

var imageCache = [String:UIImage]()

override func viewDidLoad() {

    super.viewDidLoad()

    requestPost()

    title = self.option

    tableView.allowsMultipleSelection = true

    tableView.scrollsToTop = true

    self.tableView.reloadData()
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    self.navigationController?.hidesBarsOnSwipe = false
    self.navigationController?.setNavigationBarHidden(false, animated: true)
}

func refresh(sender:AnyObject) {

    requestPost()

    self.refreshControl2.endRefreshing()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Return the number of rows in the section.
    return productos.count
}

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    // Define the initial state (Before the animation)
    cell.alpha = 0.25

    // Define the final state (After the animation)
    UIView.animateWithDuration(1.0, animations: { cell.alpha = 1 })
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // try to reuse cell
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! BuscarCellTableViewCell

    cell.selectionStyle = .None

    //cell.nombre.text = productos[indexPath.row].nombre
    //cell.marca.text = productos[indexPath.row].marca

    //println(cell.nombre.text)

    // get the deal image
    let currentImage = productos[indexPath.row].imagen
    let unwrappedImage = currentImage
    var image = self.imageCache[unwrappedImage]
    let imageUrl = NSURL(string: productos[indexPath.row].imagen)

    // reset reused cell image to placeholder
    cell.imagen.image = UIImage(named: "")

    // async image
    if image == nil {

        let request: NSURLRequest = NSURLRequest(URL: imageUrl!)

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
            if error == nil {

                image = UIImage(data: data)

                self.imageCache[unwrappedImage] = image
                dispatch_async(dispatch_get_main_queue(), {
                    cell.imagen.image = image
                    cell.nombre.text = self.productos[indexPath.row].nombre
                    cell.marca.text = self.productos[indexPath.row].marca
                })
            }
            else {
                cell.nombre.text = self.productos[indexPath.row].nombre
                cell.marca.text = self.productos[indexPath.row].marca
            }
        })
    }

    else {
        cell.imagen.image = image
        cell.nombre.text = self.productos[indexPath.row].nombre
        cell.marca.text = self.productos[indexPath.row].marca
    }

    return cell

}

func requestPost () {

    let request = NSMutableURLRequest(URL: NSURL(string: "http://www.web.es/productos_by_category.php")!)
    request.HTTPMethod = "POST"
    let postString = "category="+option
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            //println("error=\(error)")
            return
        }

        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)!
        // JSON RESULTADO ENTERO
        //println("responseString = \(responseString)")

        self.productos = self.parseJsonData(data)

        // Reload table view
        dispatch_async(dispatch_get_main_queue(), {
            self.tableView.reloadData()
        })
    }
    task.resume()
}

func parseJsonData(data: NSData) -> [Producto] {
    var productos = [Producto]()
    var error:NSError?

    let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary

    // Return nil if there is any error
    if error != nil {
        println(error?.localizedDescription)
    }

    // Parse JSON data
    let jsonProductos = jsonResult?["lista_productos"] as! [AnyObject]
    for jsonProducto in jsonProductos {

        let producto = Producto()
        producto.nombre = jsonProducto["nombre"] as! String
        producto.imagen = jsonProducto["imagen"] as! String
        producto.marca = jsonProducto["marca"] as! String
        producto.distribuidor = jsonProducto["distribuidor"] as! String
        producto.linea = jsonProducto["linea"] as! String
        producto.precio = jsonProducto["precio"] as! String

        productos.append(producto)
    }

    return productos
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "verProducto" {
        if let indexPath = self.tableView.indexPathForSelectedRow() {
            let destinationController = segue.destinationViewController as! MarcaProductoViewController
            //println(productos[indexPath.row].nombre)
            println(indexPath)
            destinationController.nombre = productos[indexPath.row].nombre
        }
    }
}
提前感谢,

问候。

试试这个方法

 if segue.identifier == "verProducto"{  
       if let indexPath = tableView.indexPathForCell(sender as! BuscarCellTableViewCell){    
           var detailsVC = segue.destinationViewController as! MarcaProductoViewController  
      }  
 }

如果segue.identifier==“verProducto”{if let indexath=tableView.indexPathForCell(发送方为!BuscarCellTableViewCell){var detailsVC=segue.destinationViewController为!marcaproductivewcontroller}}请将此作为“应答”发布,因为它起作用了,我想把它标记为解决方案。非常感谢@EICaptainok…很高兴它有帮助:)谢谢你的回答!你能解释一下为什么OP问题中的方法不起作用吗?我在几本教程中都看到过。