Mert Diricanlı
Mert Diricanlı

Reputation: 85

How to style a UITableViewCell different?

I'm trying to set a different style for my active object in a TableView. I tried setting a flag for my object (myObject.isActive) and read it in my custom UITableViewCell like this;

var myArray = [MyObject]()

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "myCustomCell", for: indexPath) as? myCustomCell {
        if myArray.count > 0 {
            // Return the cell
            let myObject = myArray[indexPath.row]
            cell.updateUI(myObject: myObject)

            return cell
        }
    }

    return UITableViewCell()
}

myCustomCell:

func updateUI(myObject: MyObject){
    if myObject.isActive { 
        self.selectedCell()
    }
}

func selectedCell() {
    labelTitle.font = UIFont(name: "Montserrat-Medium", size: 32)
    labelTitle.textColor = UIColor(hex: 0x64BA00)
}

This works great when the tableView data loads. But when I scroll the tableView other cells are also styling differently. How can I solve this?

Upvotes: 0

Views: 57

Answers (1)

rmaddy
rmaddy

Reputation: 318955

Cells get reused. You need to handle all possibilities. Your updateUI method changes the cell if myObject is active but you make no attempt to reset the cell if it isn't.

You need something like:

func updateUI(myObject: MyObject){
    if myObject.isActive { 
        selectedCell()
    } else {
        resetCell()
    }
}

And add:

func resetCell() {
    // Set the cell's UI as needed
}

Another options is to override the prepareForReuse method of the table cell class. That method should reset the cell to its initial state.

Upvotes: 4

Related Questions