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

标签 ios uitableview swift

此代码从一个 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)中尝试过这个并得到了一个单元格。

关于ios - 在 swift 中选择时,Tableview 单元格返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29660072/

相关文章:

ios - 尝试开始扫描 Chromecast 设备时出错

ios - "Use of undeclared identifier ' Braintree '"在不使用 CocoaPods 的情况下手动集成 Braintree 后出现错误

ios - UIStackView 表单布局

ios - iOS Playgrounds 是否支持 UIView 动画?

ios - UITableViewCell 无意中在不需要的行上放置了复选标记

swift - parse.com 中的字典字段

ios - 如何以编程方式让 UITableView 滚动到特定部分

ios - 在 TableView 中按距离排序

ios - 以编程方式快速调用 drawRect()

ios - Swift View Controller 初始化程序问题