2017-05-16 43 views
1

我试图识别哪个tableviewcell被选中,然后我想获取该单元的标签值并将其传递给下一个视图控制器。我的单元格的标签值为string,数值为Int。我正在使用Firebase数据库来获取所有数据。识别哪个tableviewcell被选中并将值传递给另一个viewcontroller

我的代码:

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

回答

0

试试这个:

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

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

你必须创建在目标视图控制器和存储变量这些变量在移动到目标视图控制器之前的数据。 此链接将为您提供帮助。

+0

我明白我要做的事谢谢你的线索!但是当我尝试覆盖prepareForSegue func时,我遇到了一个问题。 –

+0

随意发布问题在stackoverflow。:) –

+0

我发现它。这是一个Swift 3更新代码。 '重写func prepare(for segue:UIStoryboardSegue,sender:Any?)'而不是我用过的东西。 –

相关问题