【问题标题】:Send different nibs in a function swift 3在函数swift 3中发送不同的笔尖
【发布时间】:2017-08-01 04:15:18
【问题描述】:

我有一个 tableView 需要包含两个不同的视图,第一个的名称是 CustomTableViewCell 第二个是 CustomDeliveryTableViewCell 我希望我的变量采用两个单元格,我不明白这个错误。 这是我的功能

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{

    var cell: UITableViewCell
    cell = Bundle.main.loadNibNamed("CustomTableViewCell", owner: self, options: nil)?.first as! UITableViewCell

    if (!self.appReady)
    {
        return cell
    }
    let arrayOfCard = self.selectedCard(section: indexPath.section, row: indexPath.row)
    let json:JSON = JSON(arrayOfCard)
    if (json[0]["cards"][indexPath.row]["category"] == "delivery")
    {
        cell = Bundle.main.loadNibNamed("CustomDeliveryTableViewCell", owner: self, options: nil)?.first as! CustomTableViewCell
    }
    cell = fillCell(cell: cell, json: json, index: indexPath.row)
    return cell
}

我的函数fillCell就是这样的原型

func fillCell(cell: CustomTableViewCell, json:JSON, index:Int) -> 自定义TableViewCell

编辑

这里是实际fillCell函数的代码

    func fillCell(cell: UITableViewCell, json:JSON, index:Int) -> UITableViewCell {
    if (json[0]["cards"][index]["category"] == "train")
    {
        if let type = json[0]["cards"][index]["category"] as JSON?
        {
            cell.labelType.text = type.string
        }
        if let departureStation = json[0]["cards"][index]["train"]["departure"]["station"] as JSON?
        {
            cell.labelDepartureStation.text = departureStation.string
        }
    // Do some code
    }
    else if (json[0]["cards"][index]["category"] == "delivery")
    {
        //Do some code
        return cell
    }
    else{
        //Do some code
        return cell
    }
}

【问题讨论】:

  • 请发布实际代码而不是(或附加于)屏幕截图。使人们更容易将代码复制到答案中。谢谢。
  • 你的代码很混乱。您可能想尝试整理一下,因为不清楚您要做什么。例如,与其到处传递 JSON,不如考虑在加载 JSON 时创建对象(结构/枚举)。这将使您更容易看到正在发生的事情。此外,您不需要从fillCell返回值

标签: swift uitableview swift3 uicollectionviewcell xib


【解决方案1】:

您的初始分配创建一个CustomDeliveryTableViewCell 类型的cell

if 块中,您尝试将CustomTableViewCell 分配给同一个变量。这仅在CustomTableViewCellCustomDeliveryTableViewCell 的子类时才有效

当您调用fillCell( 时,它期待CustomTableViewCell,但cellCustomDeliveryTableViewCell

如果您声明var cell: UITableViewCell,那么您可以为其分配任何一种类型。

【讨论】:

  • 如果这样做,我需要更改fillCell的原型=>CustomTableViewCell将变为UITableViewCell。如果我这样做,我的函数无法编译,'UITableViewCell 类型的值没有成员 labelDepartureStation 我理解错误,但我不知道如何修复它
  • 您能否将代码添加到您的问题中?我不想把它全部输入答案!
猜你喜欢
  • 1970-01-01
  • 2013-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-21
  • 1970-01-01
  • 2010-10-07
相关资源
最近更新 更多