Home > OS >  Insert row in UITableViewController without replacing row - SWIFT
Insert row in UITableViewController without replacing row - SWIFT

Time:06-27

In my app I have a data pull from Firebase. I have a UITableViewController and would like to insert in a row a text from within the app. The data pull would be like this (please excuse the bad example but I cannot go into too much detail ..)

The original data pull:

Row 1: abc

Row 2: def

Row 3: ghi

Row 4: jkl

Row 5: mno

What I would like to achieve:

Row 1: abc

Row 2: def

Row 3: text from the app

Row 4: ghi

Row 5: jkl

Row 6: text from the app

Row 7: mno

How can I achieve this? I was trying to do something like this in cellForRowAt

if indexPath.row % 3 == 0 {
cell.text = "custom text"
}

But this is replacing every 3rd rows content. I would like to put a row in between, so to speak.

CodePudding user response:

You can modify your server data with local data.

var serverData = ["a","b","c","d","e","f","g","h","i","j","k","l","m"]
let localAppData = ["1","2","3","4","5","6","7","8","9","10"]

var modified = [String]()
var counter = 0
for index in 1...serverData.count {
    let value = serverData[index - 1]
    if index % 3 == 0 && index != 0 {
        if counter < localAppData.count {
            modified.append(localAppData[counter])
        }else{
            modified.append(value)
        }
        counter  = 1
    }else{
        modified.append(value)
    }
}

serverData.removeAll()
serverData.append(contentsOf: modified)
print(serverData) //["a", "b", "1", "d", "e", "2", "g", "h", "3", "j", "k", "4", "m"]

if counter < localAppData.count {
    // Appeds the remain local data to your serverData
    serverData.append(contentsOf: localAppData[counter...localAppData.count-1])
}
print(serverData) //["a", "b", "1", "d", "e", "2", "g", "h", "3", "j", "k", "4", "m", "5", "6", "7", "8", "9", "10"]

Note: After modification you have to reload the tableView

CodePudding user response:

You can update the datasource by inserting the value at 3rd position and use that datasource in cellforrowat

var a = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
         var temp = a
        for (ind, _) in a.enumerated() {
            if ind % 3 == 0 && ind != 0 {
                temp.insert("current text", at: ind)
            }
        }
print(temp) // Prints ["a", "b", "c", "current text", "d", "e", "current text", "f", "g", "h", "i"]
  • Related