2017-09-16 73 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 
    }