簡體   English   中英

如何將不同的單元格添加到tableview?

[英]How to add different cell to tableview?

我有一個 tableview,在重新加載 tableview 之后我正在從 firebase 下載數據,但我也想向 tableview 添加更多不同的單元格。 例如我的數據計數是六,我想添加到第二行和第五行不同的單元格。 最后我想顯示八個單元格。

我試過這段代碼;

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data?.count ?? 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 1 {
        let cell = myTableView.dequeueReusableCell(withIdentifier: "makeLiveWallpaper") as! LiveWallTableViewCell
        if indexPath.row == 1 {
            cell.titleLabel.text = "Let's make LiveWallpaper"
        }
        return cell
    }else{
        if let cell = myTableView.dequeueReusableCell(withIdentifier: "CategoryTableViewCell", for: indexPath) as? CategoryTableViewCell{
            cell.category = category(at: indexPath)
            cell.delegate = self
            cell.setScrollPosition(x: offsets[indexPath] ?? 0)
            return cell
        }
    }
    return UITableViewCell()
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == 1 {
        return 140
    }else{
        return 255
    }
}

但它不是添加新單元格,而是在單元格上覆蓋

獲得數據后,請更新您的數據源,如下所示:

data.insert("", at: 1)
data.insert("", at: 4)
self.tableView.reloadData()

更新您的數據源方法

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 1 {
        // your custom Cell
        return cell
    } else if indexPath.row == 5 {
        // you custom Cell
        return cell
    } else {
        // normal cell
    }
    return UITableViewCell()
}

希望它會幫助你。

暫無
暫無

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

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