在Swift中切换自定义单元格

mar*_*tin 0 xcode uitableview ios swift

我试图在swift中切换两个自定义单元类,但我似乎无法弄清楚如何返回单元格.

我的代码看起来像这样,错误在最后一行:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{

    if istrue{
    var cell: CustomTableCell = self.tv.dequeueReusableCellWithIdentifier("cell") as CustomTableCell

        let data = myList[indexPath.row] as Model

        cell.customLabel.text = data.username
        cell.dateLabel.text = printDate(data.date)
        return cell

    }else{
        var cell: CustomTableCell2 = self.tv.dequeueReusableCellWithIdentifier("cell") as CustomTableCell2

        let data = myList[indexPath.row] as Model

        cell.titleLabel.text = data.username
        cell.dateLabel2.text = printDate(data.date)

     return cell
    }

}return nil
Run Code Online (Sandbox Code Playgroud)

我也尝试在最后一行"返回单元格"并删除if-和else语句中的另外两行"返回单元格",但这不起作用,它只是给我错误说"单元格"是一个未解决的标识符.

我之前从未这样做过,所以我不确定这是否也是解决问题的正确方法.

任何有关如何进行的建议将不胜感激.

Ant*_*nio 5

定义一个UITableViewCell类型的变量并在if和else分支中初始化它,然后将其用作返回值:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{

    var retCell: UITableViewCell

    if istrue{
        var cell: CustomTableCell = self.tv.dequeueReusableCellWithIdentifier("cell") as CustomTableCell

        let data = myList[indexPath.row] as Model

        cell.customLabel.text = data.username
        cell.dateLabel.text = printDate(data.date)

        retCell = cell

    }else{
        var cell: CustomTableCell2 = self.tv.dequeueReusableCellWithIdentifier("cell") as CustomTableCell2

        let data = myList[indexPath.row] as Model

        cell.titleLabel.text = data.username
        cell.dateLabel2.text = printDate(data.date)

        retCell = cell
    }

    return retCell
}
Run Code Online (Sandbox Code Playgroud)

请注意,您无法返回,nil因为此方法的返回类型是非可选的UITableViewCell,因此它必须始终是(派生自的类)的实例UITableViewCell.

或者,您可以像在每个if和else分支上一样返回单元格,但是return从if/else范围中删除结尾- 不需要它.此外,在您的代码中,它也是错误的,因为在方法范围之外.

个人注意事项:在函数中我通常会避免return在正文中间的语句,最后选择单个退出路径 - 这只是个人偏好,所以请随意选择您喜欢的那个.