使用segue和didSelectRowAt将数据从一个表视图传递到另一个

时间:2018-12-08 23:14:25

标签: ios swift

我已经在屏幕上显示了地铁站的列表,我想要做的是单击不同的站时,他们可以将其信息传递到第二个表格视图并显示,如何使用segue和didselectRowAt做到这一点? / p>

tablecell类

class LandmarksTableViewCell: UITableViewCell {

    @IBOutlet weak var LandmardsImage: UIImageView!
    @IBOutlet weak var LandmarksLabel: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

metrostationViewController

    class MetroStationsViewController: UITableViewController{
    let wmataapimanager = WmataAPIManager()
    let locationDetector = LocationDetector()
    var stations = [Station](){
        didSet{
            tableView.reloadData()
        }
    }
   var landmarks = [Landmark]()
    override func viewDidLoad(){
        super.viewDidLoad()
        wmataapimanager.delegate = self as FetchStationsDelegate
        locationDetector.delegate = self as LocationDetectorDelegate
        fetchStation()
    }

    private func fetchStation(){
        locationDetector.findLocation()
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 120
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

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

        let station = stations[indexPath.row]

        cell.StationLabel.text = station.name
        //cell.LaiLabel.text = String(station.Lat)
        //cell.LonLabel.text = String(station.Lon)


        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("you select: \(indexPath.row)")
        let selectStation = stations[indexPath.row]
        let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell


    }

    }

1 个答案:

答案 0 :(得分:0)

didSelectRowAt委托方法中执行segue,并在发件人通过所选电台时进行

performSegue(withIdentifier: "identifier", sender: stations[indexPath.row])

然后您应该在目标ViewController中具有变量,并且可以在准备segue方法时将该变量分配为垂头丧气的发件人

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "identifier" {
        let destinationVC = segue.destination as! DestinationViewController
        destinationVC.station = sender as! Station
    }
}