UIButton backgroundColor reseted after setSelected is called

I've got a very weird behavior with a tableview cell that contains a button that behaves like a radio button.

When the user taps on a cell, I switch the button's custom selected state (my own variable in my ViewModel, not the cocoa's selected state) and change the background color of the button.


If I use selectionStyle = .none, everything works fine, but when I use .default with a custom view (a simple UIView() with a color), the cell is highlighted on selection and returns to its default state. During this animation, the button's background color changes accordingly, but then reverts to is selected state right away. The code that changes the selected state for the button is only called once :



func set(selectedState: Bool) { UIView.animate(withDuration: 0.2) { 
     self.actionButton.backgroundColor = selectedState ? Palette.MapBannerOption.selectedButtonBackground.uicolor : Palette.MapBannerOption.unSelectedButtonBackground.uicolor 
     self.actionButton.setTitle(selectedState ? "S" : nil, for: .normal) } 
}


this method is called in the delegate's didSelectRowAtIndexPath as follows :



func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
     tableView.deselectRow(at: indexPath, animated: true) 
     if let col = viewModel.handleRowTap(for: tableView, at: indexPath), 
        let cell = tableView.cellForRow(at: indexPath) as? MapBannerCellSelectable { 
          cell.set(selectedState: col.selectedState) 
     } 
}


I added the setTitle just for test reasons. It gets weirder : the button's label works as expected (the "s" appears and disappears following the method's calling)

The setSelected(_ selected: Bool, animated: Bool) is not overridden (it doesn't change a thing if I do). It does not work either if I remove the animation block, or if I call it on the main thread (which is already the case I guess) However, if I delay the animation by 0.5 (after the setSelected(_ , animated:) finished), it works. If I delay the animation with 0.2 (before the setSelected(_, animated:) finished), it does not work. It seems that the selection/deselection of the cell interferes with the button's drawing, but I can't figure out how 😟


I do want to create a custom selection animation with selectionStyle = .default, though I could. I just want to understand what's wrong here :-/ If you have any insights, that would be very much appreciated.


Thanks.

Replies

Hi again ;-)

If anyone has even the tyniest clue, I'm in ;-)

Thanks.