简体   繁体   中英

How to add different cell to tableview?

I have a tableview and I'm downloading data from firebase after that I reload tableview but I want to add more different cell to tableview too. For example my datas count is six and I want to add to second row and fifth row different cell. In the end I want to show eight cell.

I tried this code;

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

But it is not adding new cell it is over write on cell

Once you got the data update your dataSource like given below:

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

update your Data Source Method

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()
}

Hope it will hep you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM