1

I have a cell structure that looks like this:

enter image description here

The contentView has the same backgroundColor as the tableView background (blue) and the nested view has a white color with cornerRadius and 5p autoLayout margin all around, resulting in what looks like separated cells, sort of like separated buttons in a row (let me know if you need an image).

Whenever I click a cell I would like that cell to be highlighted with another color. Normally this would be done in the storyBoard under the attribute inspector selection. But this is strictly connected to the cell and doesn't effect the nested views. I can make the views transparent or remove them altogether and it works, but then I miss out on the illusion of separated cells.

I read here How to add spacing between UITableViewCell that you can use sections to separate the cells. Nice, but the thing is I'm using RxSwift and if I want the numberOfSections delegate, then I also need cellForRowAt and numberOfRows and those sort of conflict with my Rx tableView.

I tried doing it programmatically by adding a tag to my nested view, fetching it like this:

var myView = self.contentView.viewWithTag(1) //self is cell

and then set the color in the Rx subscription:

    cell?.layer.backgroundColor = UIColor.green.cgColor

But this just didn't work. Any ideas how to solve this?

1 Answers1

1

Override the method func setSelected(_ selected: Bool, animated: Bool) in the cell and adjust the views how you want based on the selected attribute.

Alternatively, you could do this with rx.methodInvoked if you don't want to override the method.

At request, here is how to do it with rx.methodInvoked.

_ = rx.setSelected
    .map { $0.selected ? UIColor.gray : UIColor.white }
    .takeUntil(rx.deallocating)
    .bind(to: contentView.viewWithTag(1)!.rx.backgroundColor)

to make the above work, add the code below somewhere:

extension Reactive where Base: UITableViewCell {
    var setSelected: Observable<(selected: Bool, animated: Bool)> {
        base.rx.methodInvoked(#selector(UITableViewCell.setSelected(_:animated:)))
        .map { (selected: $0[0] as! Bool, animated: $0[1] as! Bool) }
    }
}
Daniel T.
  • 32,821
  • 6
  • 50
  • 72
  • Oh, that's really nice! It worked great :) Thanks for the tip! In setSelected, I added `if selected { self.contentView.viewWithTag(1)?.backgroundColor = UIColor.gray } else { self.contentView.viewWithTag(1)?.backgroundColor = UIColor.white }` – screenMonkey MonkeyMan May 15 '20 at 04:38
  • Oh, how does it work with rx.methodInvoked by the way? Would be nice to know :) – screenMonkey MonkeyMan May 15 '20 at 05:16