1

Essentially, I have the following UITableViewController that contains custom tableView cells with labels in them. When the cell is selected I would like the value of the cell to be passed to the next view controller where I am using it in an HTTP POST response.

What can be added to didSelectRowAt to pass the value of the selected cell to the view controller presented?

Perhaps as a variable?

The following is my code:

import UIKit

class ScheduledCell: UITableViewCell {

    @IBOutlet weak var ETALabel: UILabel!
    @IBOutlet weak var cellStructure: UIView!

    @IBOutlet weak var scheduledLabel: UILabel!
    @IBOutlet weak var testingCell: UILabel!
    @IBOutlet weak var pickupLabel: UILabel!
    @IBOutlet weak var deliveryLabel: UILabel!
    @IBOutlet weak var stopLabel: UILabel!
    @IBOutlet weak var topBar: UIView!


}

class ToCustomerTableViewController: UITableViewController, UIGestureRecognizerDelegate {

    var typeValue = String()

    var driverName = UserDefaults.standard.string(forKey: "name")!
    var structure = [AlreadyScheduledStructure]()


    override func viewDidLoad() {
        super.viewDidLoad()

        fetchJSON()


        //Disable delay in button tap
        self.tableView.delaysContentTouches = false

        tableView.tableFooterView = UIView()

    }


    private func fetchJSON() {
        guard let url = URL(string: "https://example.com/example/example"),
            let value = driverName.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
            else { return }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = "driverName=\(value)".data(using: .utf8)

        URLSession.shared.dataTask(with: request) { data, _, error in
            guard let data = data else { return }


            do {
                self.structure = try JSONDecoder().decode([AlreadyScheduledStructure].self,from:data)
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
            catch {
                print(error)
            }

            }.resume()

    }



    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return structure.count
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "scheduledID", for: indexPath) as! ScheduledCell
        let portfolio = structure[indexPath.row]
        cell.stopLabel.text = "Stop \(portfolio.stop_sequence)"
        cell.testingCell.text = portfolio.customer
        return cell

    }

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


        let portfolio = structure[indexPath.row]
        let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "scheduledDelivery")

        print(portfolio.customer)
        controller.navigationItem.title = navTitle
        navigationController?.pushViewController(controller, animated: true)
    }


    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 200.0
    }

}

3 Answers3

3

Create public variables for the data which you want to pass to the scheduledDelivery controller.Then set them inside didselect delegate method. Let say if you want to pass portfolio.customer. Declare following public variable on scheduledDelivery controller.

public var portfilio:String?

Then set value to that variable from the didselect method like this,

let portfolio = structure[indexPath.row]
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "scheduledDelivery")
controller.portfilio = portfolio.customer
controller.navigationItem.title = navTitle
navigationController?.pushViewController(controller, animated: true)
0

add a portfolio variable to your next ViewController

   class scheduledDeleivery: UIViewController{
     var customer:String? //suposing this is customer type

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

    let portfolio = structure[indexPath.row]
    let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "scheduledDelivery") as! shcheduledDeleivery
    controller.customer = porfolio.customer //here is the customer you need to pass to next viewcontroller
    print(portfolio.customer)
    controller.navigationItem.title = navTitle
    navigationController?.pushViewController(controller, animated: true)
}
Yoel Jimenez del valle
  • 1,270
  • 1
  • 9
  • 20
  • I keep getting the error Value of type `'UIViewController' has no member 'portfolio'` –  Jun 26 '19 at 19:21
  • Not exactly, I need the value of structure[index.row] to be passed –  Jun 26 '19 at 20:05
  • porfolio is of type `AlreadyScheduledStructure` so in your next viewcontroller must have a variable of that type to passed from tableViewController, so when you are using this line `let portfolio = structure[indexPath.row]` you have that value that need to be pases to next viewcontroller, with the line 'let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "scheduledDelivery") as! shcheduledDeleivery controller.porfolio = porfolio' this one set the value readed here to the next one. – Yoel Jimenez del valle Jun 26 '19 at 20:10
  • The problem with this is all of the value of AlreadyScheduledStructure are being passed –  Jun 26 '19 at 20:16
  • It is passing the values of the entire struct, when I only need customer `AlreadyScheduledStructure: Codable { let customer: String let PickedUpNUM: String` –  Jun 26 '19 at 20:22
  • check the edit. you should make it more clear in the question to let us know that you want to pass only the string – Yoel Jimenez del valle Jun 26 '19 at 20:28
  • Is there a way I make this variable available as a public variable for multiple view controllers? –  Jun 26 '19 at 22:15
  • that's another question dude, ask it here not use the same question to resolve other problem, and it solve your current problem you should bote the answer – Yoel Jimenez del valle Jun 26 '19 at 23:15
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/195652/discussion-between-kjoe-and-relson-james). – Yoel Jimenez del valle Jun 27 '19 at 20:14
0

You can store the cell's data as a variable and then in prepare for segue function pass it to the other ViewController. If you call this in prepare for segue it will automatically do it every time you try to access that segue.

var nameOfVar : String = ""

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var secondVC = segue.destination as! YourSecondViewController
secondVC.variable = nameOfVar }

Hope I've helped :)

kieu
  • 1
  • 3