Search code examples
iosswift3xcode8

How to get the indexPath of tableView and use the indexPath on the metod prepare(for segue: )


I have a Tableview that shows a section with 7 rows, what I want to do is that when I press row 0 I send it to another view, all the information in the table is loaded by code using fixes, my question is how can I get the indexPath in the "prepare ()" method and how the segue should be done in a programmatic way.

This is my class where I have all the code in my TableView:

//
//  ControlTablaPrincipalTableViewController.swift
//  Seccion 15
//
//  Created by Barbatos on 7/10/18.
//  Copyright © 2018 Seccion 15. All rights reserved.
//

import UIKit

class ControlTablaPrincipalTableViewController:UITableViewController {

    var titulos : [String] = ["Caja de ahorro","Blog de la Seccion 15","Iniciar Sesion","Galeria de eventos","Convenios", "Ubicacion", "Contactanos"]

    var imagenes : [UIImage] = [#imageLiteral(resourceName: "caja"),#imageLiteral(resourceName: "blog"),#imageLiteral(resourceName: "sesion"),#imageLiteral(resourceName: "galeria"),#imageLiteral(resourceName: "convenio"),#imageLiteral(resourceName: "ubicacion"),#imageLiteral(resourceName: "contacto")]

    override func viewDidLoad() {

        super.viewDidLoad()

        self.tableView.dataSource = self
        self.tableView.delegate = self

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return titulos.count

    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
        cell?.imageView!.image = imagenes[indexPath.row]
        cell?.textLabel?.text = titulos[indexPath.row]

        return cell!
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let alert = UIAlertController(title: "Celda seleccionada", message: "Se selecciono la celda \(indexPath.row)",preferredStyle: .alert)

        let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)

        alert.addAction(okAction)
        self.present(alert, animated: true, completion: nil)
    }

This is my didSelectRowAt method where I programmed an alert that will show me which cell I am programming:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let alert = UIAlertController(title: "Celda seleccionada", message: "Se selecciono la celda \(indexPath.row)",preferredStyle: .alert)

        let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)

        alert.addAction(okAction)        
        self.present(alert, animated: true, completion: nil)   
   }

This is the prepare method where I try to recover the selected cell and program an if to be able to use my segue:

overrider func prepare(for segue: UIStoryboardSegue, sender: Any?){

    if let indexPath = tableView.indexPathForSelectedRow{
        let selectedRow = indexPath.row
            if(selectedRow == 0){
               segue.destination as? CajadeAhorroViewController 
            }
    }

}

The identifier of my segue is "caja":

enter image description here


Solution

  • I think you want to just perform the segue inside the tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) function...

    override func tableView(_ tableView: UITableView, 
               didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
        case 0:
            performSegue(withIdentifier: "caja", sender: nil)
        case 1:
            performSegue(withIdentifier: "whatever you set this identifier to", sender: nil)
        // cases for all the different rows...
        }
    }
    

    If you only have one segue and you need to switch the variables of the view controller it shows differently based on the cell selected

    overrider func prepare(for segue: UIStoryboardSegue, sender: Any?){
        if let indexPath = tableView.indexPathForSelectedRow,
           let destination = segue.destination as? CajadeAhorroViewController {
            switch indexPath.row {
            case 0:
                // destination is the "CajadeAhorroViewController", set its properties for how you want it.
            case 1: 
            // ... all 7 cases ...
            }
        }
    }