2017-09-16 29 views
-2

我試圖在數組中找到UITableViewCell文本。問題是,不管我一下什麼細胞,array.index(of:)總是返回1array.index(of:)無法正常工作

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 
    if let text = cell.textLabel?.text { 
     let indexOfCellString = event.index(of: text) 
     print (indexOfCellString!) 
    } 

} 
//here is my attempt to set the cell text: 
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ 

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 
    if eventIndex.indices.contains(indexPath.row) == true { 
    cell.textLabel?.text = event [indexPath.row] 
    } 

    return cell 
} 

事件是,我試圖在搜索和查找單元格文本的數組。 和單元格的文本總是在事件的索引中。因爲我的tableview從事件數組中讀取信息。因此它不應該總是返回1. 我做錯了什麼?

+3

沒有人可以幫助你沒有更多的信息。你還沒有解釋「事件」是什麼。你還沒有提供任何關於「text」包含的細節。您發佈的代碼無效。什麼是「自我」)? – rmaddy

+0

它應該返回cell.textlable.text所在的事件索引。 但無論我點擊哪個表格行,它總是返回1. 不用說,表格行具有不同的字符串 – Farbod

+0

您的企圖設置單元格的標籤文本? – rmaddy

回答

1

千萬不要在cellForRowAt之外使用dequeueReusableCell。只需訪問數據模型中的數據即可。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    if eventIndex.indices.contains(indexPath.row) == true { 
     let text = event[indexPath.row] 
     if let indexOfCellString = event.index(of: text) { 
      print("Found index: \(indexOfCellString)") 
     } else { 
      print("text not found") 
     } 
    } 
}