Jordan Lewallen
Jordan Lewallen

Reputation: 1851

Adjust row count for TableView dynamic content

I have a page with 3 TableCells (Image at bottom): The first cell filled with dynamically loaded content from Firebase for the profile image, username, and minutes watched which is populated in my userModel array. I am having an issue setting the numberOfRowsInSection for the table because the first cell is dynamic.

When I try and count the number of cells, I add 2 because I have two static cells (the merch cell and the log out cell) that I know I need to display. But since userModel.count starts off at 0, the app crashes due to row indexing the dynamic content before the userModel.count array is populated:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return userModel.count + 2
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "leaderboardCell", for: indexPath) as! LeaderboardCell
            cell.profileImage.image = userModel[indexPath.row].photo
            cell.profileImage.layer.cornerRadius = cell.profileImage.frame.size.width/2
            cell.userName.text = userModel[indexPath.row].username
            cell.watchTime.text = userModel[indexPath.row].watchTime
            cell.profileLeaderboardContainer.layer.cornerRadius = 3.0
            return cell
        } else if indexPath.row == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "merchCell", for: indexPath) as! MerchCell
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "logoutCell", for: indexPath) as! LogoutCell
            cell.logoutButton.layer.cornerRadius = 3.0
            return cell
        }

The app crashes at:

cell.profileImage.image = userModel[indexPath.row].photo

which completely makes sense because there is no index location of 2 before any data is loaded into that model. But my question is how do I prevent such an error with a dynamic array in the first table cell? Thanks!

P.S if I have my row count as just return userModel.count the top cell loads perfectly fine with the dynamic content but the other two cells do not load at all (this makes sense because the count inside the array is 0) so indexes 1 and 2 are not displayed

enter image description here

Upvotes: 0

Views: 255

Answers (1)

crperez
crperez

Reputation: 127

You could do:

if userModel.count > indexPath.row {
    cell.profileImage.image = userModel[indexPath.row].photo
} else {
    cell.profileImage.image = nil //or whatever default value
}

Or if userModel is an Optional:

if let count = userModel?.count, count > indexPath.row {
    cell.profileImage.image = userModel[indexPath.row].photo
} else {
    cell.profileImage.image = nil //or whatever default value
}

Upvotes: 1

Related Questions