簡體   English   中英

在Swift中自定義單元格之間切換

[英]Switching between custom cells in 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

我也嘗試過在最后一行“返回單元格”,並在if和else語句中刪除“返回單元格”的其他兩行,但這沒有用,這只是給我一個錯誤,說“單元格”是無法解析的標識符。

我以前從未做過此事,因此我不確定這是否是解決問題的正確方法。

任何建議如何進行將不勝感激。

定義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
}

請注意,您不能返回nil因為此方法的返回類型是非可選的UITableViewCell ,因此它必須始終是UITableViewCell (從其派生的類)的實例。

另外,您也可以像在每個if和else分支上一樣返回單元格,但是將結束return從if / else范圍內刪除-不需要。 此外,在您的代碼中,由於方法范圍之外,它也被放錯了位置。

個人說明:在函數中,我通常避免在主體中間使用return語句,而是在末尾使用單個退出路徑-這只是個人喜好,因此可以隨意選擇自己喜歡的那個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM