识别选择了哪个表视图单元格,并将值传递给另一个视图控制器



我正在尝试识别选择了哪个表视图单元格,然后我想获取该单元格的标签值并将其传递给下一个视图控制器。我的单元格有一个string的标签值和一个Int的数字值。我正在使用Firebase数据库来获取所有这些数据。

我的代码:

import UIKit

class PlacesTableViewController: UITableViewController {
 //MARK: Properties
    @IBOutlet weak var placesTableView: UITableView!
var places = [Places]()
override func viewDidLoad()
    {
        super.viewDidLoad()


        // Loads data to cell.
        loadData()
    }
override func numberOfSections(in tableView: UITableView) -> Int
    {
        return 1
    }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {   
        //return the number of rows
        return places.count
    }
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        // Table view cells are reused and should be dequeued using a cell identifier.
        let cellIdentifier = "PlacesTableViewCell"
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? PlacesTableViewCell  else {
            fatalError("The dequeued cell is not an instance of PlacesTableView Cell.")
        }
        let place = places[indexPath.row]
        cell.placeLabel.text = place.name
        cell.ratingControl.rating = place.rating
        return cell
    }
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        print(places[indexPath.section])
        self.performSegue(withIdentifier: "ShowCommentsTableViewController", sender: nil)
    }
}

你可以按照这个线程做有用的 send-data-from-tableview-to-detailview-swift

在移动到目标视图控制器

之前,您必须在目标视图控制器中创建变量并将数据存储在这些变量中。此链接将帮助您。

试试这个:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        let selectedPlace = places[indexPath.section]
        self.performSegue(withIdentifier: "ShowCommentsTableViewController", sender: selectedPlace)
    }
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let selectedPlace = sender as? Places,
        let destViewController = segue.destination as? SecondViewController {
        destViewController.place = selectedPlace
    }
}

最新更新