0

I have a UITableView where data is loaded from a database, a JSON. How do I get this when I select a line, which is taken in another view?

The automarke is to be selected in the tableview and displayed in the label of the other view.

class AutoMarkeTableView: UITableViewController {
    var items = [[String:AnyObject]]()

    @IBOutlet var myTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "URL_LINK")!
        let urlSession = URLSession.shared

        let task = urlSession.dataTask(with: url) { (data, response, error) in
            // JSON parsen und Ergebnis in eine Liste von assoziativen Arrays wandeln
            let jsonData = try! JSONSerialization.jsonObject(with: data!, options: [])
            self.items = jsonData as! [[String:AnyObject]]

            // UI-Darstellung aktualisieren
            OperationQueue.main.addOperation {
                self.tableView.reloadData()
            }
        }

        task.resume()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "markeCell", for: indexPath)

        let item = items[indexPath.row]

        cell.textLabel?.text = item["makename"] as? String

        return cell
    }
}

class FahrzeugAngabenView: UIViewController {
    @IBOutlet weak var itemMarkeLabel: UILabel!
}

View1

View2

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    You need to implement `optional func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)`. – Larme May 10 '17 at 13:47
  • Possible duplicate of [Send data from TableView to DetailView Swift](http://stackoverflow.com/questions/28430663/send-data-from-tableview-to-detailview-swift) – Larme May 10 '17 at 13:47
  • Unfortunately I do not get it, the example tried in the link, but no success. Does anyone else have an idea? And sorry because of my english, google transate The autarke will be displayed in the label – oligabler May 10 '17 at 15:31

1 Answers1

0

You could temporarily save the selected item in a variable. Something like this:

var selectedItem: Item?
func tableView(tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedItem = items[indexPath.row]
    self.performSegue(withIdentifier: "auto", sender: self)
}

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

    if segue.identifier == "auto" {
        let destVc = segue.destination  as! FahrzeugAngabenView

        destVc.selectedItemName = selectedItem.title
        selectedItem = nil
    }
 }

Not the most elegant solution, but i would expect this to work.

bughana
  • 324
  • 5
  • 12