Skip to main content
 首页 » 编程设计

ios之在 swift 中选择时,Tableview 单元格返回 nil

2024年01月01日70落叶无声

此代码从一个 json 文件中读取并在所有单元格中返回“名称”值,这工作正常,但是当我选择该值时它一直返回 null,我想获取该值。我在其他问题中尝试了一些其他解决方案,因为它们在 Objective C 中,而且速度很快,但我尝试过但根本没有用。我想要的只是单元格内的值。 我也想传递“id”的值,即所选单元格的数据[“id”],这可能吗。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("ImageCell", forIndexPath: indexPath) as UITableViewCell //1 
 
    let data = datas[indexPath.row] 
 
    if let captionLabel = cell.viewWithTag(100) as? UILabel { 
        if let caption = data["name"].string{ 
            captionLabel.text = caption 
        } 
    } 
 
    return cell 
} 
 
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
 
    let indexPath = self.tableView.indexPathForSelectedRow(); 
 
    let currentCell = self.tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!; 
 
    println(currentCell.textLabel!.text) 
    self.viewofloc.hidden = true 
} 

请您参考如下方法:

方法 tableView:didSelectRowAtIndexPath:为您选择的单元格提供索引路径。无需使用 self.tableView.indexPathForSelectedRow 重新计算。

试着用这个编辑你的 tableView:didSelectRowAtIndexPath::

 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
        let currentCell = self.tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!; 
    } 

我已经在新的 Xcode 项目(Master-Detail Application)中尝试过这个并得到了一个单元格。