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



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

表格单元格类

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

}
}

didSelectRowAt中,委托方法执行分段,并作为发送方通过所选站点

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

然后您应该在目标ViewController中有一个变量,并且您可以在prepare for segue方法中将该变量分配为下转换的发送方

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

最新更新