Show two different custom cells in same uitableview - swift firebase

前端 未结 6 1544
心在旅途
心在旅途 2021-02-06 20:15

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

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-06 20:25

    @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{
            // Updates
            let cell:updateTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! updateTableViewCell
            let update = updates[indexPath.row]
            cell.nameLabel.text = update.addedByUser
            return cell
        } else {
            // UpdatesTask
            let cellTask:tasksTableViewCell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! tasksTableViewCell
            let updateTask = updatesTask[indexPath.row-updates.count]
            cellTask.nameLabel.text = updateTask.addedByUser
            return cellTask
        }
    
    }
    

    This will display all cells followed by all cellTasks.


    If updates array and updatesTask array have equal number of items and you want to display them one by one you can use this:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        if indexPath.row % 2 == 0 {
            // Updates
            let cell:updateTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! updateTableViewCell
            let update = updates[indexPath.row/2]
            cell.nameLabel.text = update.addedByUser
            return cell
        } else {
            // UpdatesTask
            let cellTask:tasksTableViewCell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! tasksTableViewCell
            let updateTask = updatesTask[indexPath.row/2]
            cellTask.nameLabel.text = updateTask.addedByUser
            return cellTask
        }
    
    }
    

提交回复
热议问题