2017-09-16 39 views
0

我想獲取表格視圖單元格上的文本,然後獲取它在數組中的索引。解開UITableView單元格文本

這是我使用的代碼:

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

,但我得到了以下錯誤:可選字符串類型

  1. 價值?

這到底是怎麼回事不解開

  • 在源文件中的無效字符?還有什麼我需要打開?

  • 回答

    0
    1. 沒有必要投dequeueReusableCellUITableViewCell,因爲這是它的返回類型。

    2. cell.textLabel是可選的。然後的text屬性是可選的。

    妥善處理選配:

    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(text) 
         // do stuff with indexOfCellString 
        } 
    
        return cell 
    }