简体   繁体   中英

UitableView selected cell to the other view

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

视图1

视图2

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM