How to Skip Rows in UITableView

532 views Asked by At

I've only seen information on deleting rows or removing rows. I am trying to skip a row and display information. I haven't been able to find any information on that.

For example I have an array of products = ['Broom', 'Mop', 'Chair', 'Pan']. I want to display it in my tableview where it displays as:

Broom

skip a cell

Mop

skip a cell

Chair

skip a cell

Pan

skip a cell

I have the count times two to have enough rows and I created a second row to help with the skip process.

Here's what I have so far. However, the issue is it skips the actual item not the next cell. So it instead does:

Broom

skip a cell

Chair

skip a cell

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let index = indexPath.row

    if (index % 2) == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "productsblock", for: indexPath ) as! DetailTBCell

        return cell
    } else {
        let spacecell = tableView.dequeueReusableCell(withIdentifier: "spacingcell", for: indexPath ) as! DetailSpaceTBCell
        
        return spacecell
    }
}
1

There are 1 answers

0
aheze On

As @matt said, you should just have a data source that contains placeholders. Try something like this:

let items = ["Broom", "Mop", "Chair", "Pan"]
var expandedItems = [String]()

func expandArray() { /// call this to add placeholders
    var temporaryExpandedItems = [String]()
    for item in items {
        temporaryExpandedItems.append(item)
        temporaryExpandedItems.append("") /// add a placeholder
    }
    expandedItems = temporaryExpandedItems
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return expandedItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let index = indexPath.row
    let currentItem = expandedItems[index]

    if currentItem != "" {
        let cell = tableView.dequeueReusableCell(withIdentifier: "productsblock", for: indexPath ) as! DetailTBCell

        return cell
    } else { /// skip this placeholder
        let spacecell = tableView.dequeueReusableCell(withIdentifier: "spacingcell", for: indexPath ) as! DetailSpaceTBCell
        
        return spacecell
    }
}