【问题标题】:showing a double value in a custom cell in uitableview在uitableview的自定义单元格中显示双精度值
【发布时间】:2021-12-13 09:40:03
【问题描述】:

所以,全面披露:我是 Swift 的新手。

我正在开发一个应用程序,试图在自定义单元格中获取标签以显示 DOUBLE 值。我试图做一个 if let 条件绑定来将它从一个字符串转换为一个双精度,但我的源不是可选类型,我不能让它成为可选的。所以我不知道该怎么做。

以下是具体错误:
条件绑定的初始化程序必须具有 Optional 类型,而不是“Double”
无法分配“Double”类型的值?输入“字符串?”
初始化程序调用中没有完全匹配

这是代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DemoTableViewCell", for: indexPath) as! DemoTableViewCell
        
        cell.partNameLabel.text = parts[indexPath.row].partName
        
        // Convert string value to double
        if let value = parts[indexPath.row].partCost {
             cell.partCostLabel.text = Double(value)
        } else {
            cell.partCostLabel.text = 0.00
        }
        cell.purchaseDateLabel.text = parts[indexPath.row].purchaseDate

        return cell
    }

提前致谢!

【问题讨论】:

    标签: ios swift string uitableview double


    【解决方案1】:

    从错误来看,parts[indexPath.row].partCost 看起来已经Double - 错误告诉您 if let 仅适用于 Optional 类型。

    因此,您可以将 if let / else 块替换为:

    cell.partCostLabel.text = String(format: "%.2f", parts[indexPath.row].partCost)
    

    cell.partCostLabel.text = 0.00 不起作用,因为 Text 需要 String - 上面的代码不再需要它,但处理它的方法是 cell.partCostLabel.text = "0.00"

    最后,Cannot assign value of type 'Double?' to type 'String?' -- 我不确定发生在哪一行,但如果是 cell.purchaseDateLabel.text = parts[indexPath.row].purchaseDate 则意味着 purchaseDateDouble? 并且您正试图将其设置为期望String。您需要考虑如何将Double 转换为日期,但这个 可能是您需要if let 的地方:

    if let purchaseDate = parts[indexPath.row].purchaseDate {
      cell.purchaseDateLabel.text = "\(purchaseDate)" //you probably want a different way to display this, though
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多