2017-10-07 90 views
0

我正在使用tableView來顯示名稱列表。當用戶點擊其中一個單元格時,會彈出一個窗口,顯示更多細節。我正在使用此功能來檢查用戶點擊了哪個單元格。如何知道使用Swift在tableView中點擊哪個單元格

var selectedCell: Int? 

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    print("This cell from the chat list was selected: \(indexPath.row)") 
    selectedCell = indexPath.row 
} 

不幸的是,它似乎給予0和2之間的隨機數(我目前有三個顯示的單元格)。

你知道我怎麼知道哪個單元被點擊?

預先感謝您。

編輯:

我明白什麼是僞造我的結果。

我正在使用此功能將選定的單元格推送到另一個視圖控制器(名爲ConversationViewcontroller)。但是,segue fonction在tableView函數之前被調用,所以segue推動之前選擇的單元格。我怎麼能糾正這個?

這裏是我的賽格瑞代碼:再次

//SEGUE: Cell was selected: pass chatID 
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     if segue.identifier == "OpenChat" { 
      if let toViewController = segue.destination as? ConversationViewController { 
       toViewController.chatIdentifier = selectedCell 
      } 
     } 
    } 

感謝。

+0

您發佈的代碼是正確的代碼試試這個

var selectedCell: IndexPath override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("This cell from the chat list was selected: \(indexPath.row)") selectedCell = indexPath } 

。 'indexPath.row'將成爲您點擊的行。 – rmaddy

+0

它似乎工作正常。如果您有三個單元格,則第一個indexpath.row將爲0,第二個爲1,然後爲2. –

+0

確認將委託和數據源分配給您的表視圖 – Alexander

回答

1

,如果你想使用IndexPath

self.selectedCell?.row 
相關問題