【问题标题】:Get cell index from tableviewcell从 tableviewcell 获取单元格索引
【发布时间】:2016-12-31 15:20:55
【问题描述】:

嘿,我有这个 tableview 控制器,它可以从我的数据库中列出餐馆。我想要做的是,如果选择了单元格/行,它会打开一个关于餐厅的更多详细信息页面。出于某种原因,我无法检索索引,或者它不去 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 给我索引,这就是我所拥有的:

class HomeTableViewController: UITableViewController{


var restaurantArray = [Restaurant]()
var resTransfer: Restaurant?
var resName: String?



var dataBaseRef: FIRDatabaseReference! {
    return FIRDatabase.database().reference()
}


override func viewDidLoad() {
    super.viewDidLoad()
    title = "Home"
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Main Menu", style: .plain, target: self, action: #selector(SSASideMenu.presentLeftMenuViewController))
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    fetchRestaurants()
}

func fetchRestaurants(){
    FIRDatabase.database().reference().child("AthensRestaurants/Restaurants").observe(.value, with: { (snapshot) in
        var results = [Restaurant]()

        for res in snapshot.children{
            let res = Restaurant(snapshot: res as! FIRDataSnapshot)
            results.append(res)
        }

        self.restaurantArray = results.sorted(by: { (u1, u2) -> Bool in
            u1.name < u2.name
        })
        self.tableView.reloadData()

}) { (error) in
print(error.localizedDescription)
}
}

// MARK: - Table view data source
// MARK: - Table view data source

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return restaurantArray.count
}


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

    // Configure the cell...

    cell.configureCell(res: restaurantArray[indexPath.row])

    return cell
}




func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("Row \(indexPath.row)selected")
    resTransfer = restaurantArray[indexPath.row]
    resName = restaurantArray[indexPath.row].name
    print(resName as Any)
    performSegue(withIdentifier: "RestaurantDetailView", sender: self)
   }







override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if(segue.identifier == "RestaurantDetailView") {
      let vc = segue.destination as! RestaurantDetailViewController
       vc.resNam = restaurantArray.first?.name //instead of first should be index of cell! 
        print(vc.resNam! as String)
    }
}   
}

【问题讨论】:

  • 您已经在didSelectRowAtIndexPath 中获得了 resName ...所以只需使用vc.resNam = resName

标签: swift firebase firebase-realtime-database


【解决方案1】:

我就是这样做的,没有segue:

func showRestaurantViewControllerWith(_ id: String) {
    let storyBoard = UIStoryboard(name: "RestaurantCard", bundle: nil)
    let destinationVC = storyBoard.instantiateViewController(withIdentifier: "RestaurantCard") as! RestaurantCardViewController
    destinationVC.restaurant.id = id
    self.navigationController?.pushViewController(destinationVC, animated: true)
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.showRestaurantViewControllerWith(self.allRestaurants[indexPath.row].id)
}

【讨论】:

  • 请接受,以后可能会对某人有所帮助:) 很高兴这有帮助
【解决方案2】:

你必须使用这个函数来获取索引

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{           
           print(indexPath.row)        
}

它会给你索引。

【讨论】:

    【解决方案3】:

    首先你的代码显然是 Swift 3 所以didSelectRowAt 的签名是错误的。

    另一种解决方案是将索引路径传递为sender

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("Row \(indexPath.row)selected")
        performSegue(withIdentifier: "RestaurantDetailView", sender: indexPath)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       if segue.identifier == "RestaurantDetailView" {
          let indexPath = sender as! IndexPath
          let restaurant = restaurantArray[indexPath.row]
          let resName = restaurant.name
          print(resName!)
          let vc = segue.destination as! RestaurantDetailViewController
          vc.resNam = resName  
       }
    }
    

    或者更容易将 segue 连接到表格视图单元格。然后你可以删除didSelectRow...,因为prepare(for被直接调用,单元格作为sender参数传递。

    PS:为什么属性name 是可选的?在现实生活中,你听说过没有名字的餐厅吗?

    【讨论】:

      猜你喜欢
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多