D. Finna D. Finna - 2 months ago 21
Swift Question

Show two different custom cells in same uitableview - swift firebase

I am currently having a problem with displaying two different types of custom cells on the same uitableview.

What I have managed so far, is receiving the "updates" to the update cell, known as

cell
. I just cannot figure out how to also get numberOfRowsInSection to return two values, so both of my cells will show.

Let me explain through my code:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return updates.count
return updatesTask.count // I CANNOT DO THIS - what can I do instead?
}



override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:updateTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! updateTableViewCell
let cellTask:tasksTableViewCell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! tasksTableViewCell


let update = updates[indexPath.row]
let updateTask = updatesTask[indexPath.row]


// Example of the two different cells that need different data from firebase
cell.nameLabel.text = update.addedByUser
cellTask.nameLabel.text = updateTask.addedByUser


As you can probably see, the
let updateTask
is trying to get an
indexPath.row
but that is not possible, since I cannot have two return values in the
numberOfRowsInSection
, which is a problem because that number is referring to the place where the data is stored in my firebase database.. How can I modify this to make it work?

Hope you guys understand where I am going with this, otherwise let me know and I will try to explain better :-)

Answer

@Callam's answer is great if you want to put them in two sections.

This is the solution if you want all to be in one section.

First, in numberOfRowsInSection method you need to return the sum of those two array counts like this: return (updates.count + updatesTask.count)

Then you need to configure cellForRowAtIndexPath method like this:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    if indexPath.row < updates.count{
        let cell:updateTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! updateTableViewCell
        let update = updates[indexPath.row]
        cell.nameLabel.text = update.addedByUser
        return cell
    } else {
        let cellTask:tasksTableViewCell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! tasksTableViewCell
        let updateTask = updatesTask[indexPath.row-updates.count]
        cellTask.nameLabel.text = updateTask.addedByUser
        return cellTask
    }

}
Comments