Search code examples
swifttableviewcell

How to show separate View(box) in between tableview in Swift


In this screen how to show (blue view) in between tableview rows

design image

code: in storyboard design i have given all static data in labels and images so with this below code i am getting all cells like above screen shot, but after three cells how to show blue box view, please suggest me

import UIKit

class ViewController: UIViewController , UITableViewDataSource, UITableViewDelegate {



func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return 5
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "BidCell", for: indexPath)
    return cell
}

Solution

  • There are two ways to do that:

    1. Use a different UITableViewCell class (probably what you are looking for?)
    2. Use sections

    How?

    You can either create a new UITableViewCell prototype cell in your storyboard or do it programmatically. Create a custom UITableViewCell as such:

    class OfferTableViewCell: UITableViewCell {
    
    }
    
    // If you are not using storyboards, add the following code
    // in your viewDidLoad
    tableView.register(OfferTableViewCell.self, forCellReuseIdentifier: "your_cell_id")
    

    Then, you can dequeue the newly created cell at any index as such:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 10 // Index of the different cell
            let cell = tableView.dequeueReusableCell(withIdentifier: "your_cell_id", for: indexPath) as! OfferTableViewCell
            // Do cell configuration here
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BidCell", for: indexPath)
            return cell
        }
    }
    

    Keep in mind that this cell is going to take the place of another cell if you are using an array as datasource, so using myArray.count for your numberOfRowsInSection would result in the last array element missing. You will have to take that into account.

    Resources