2

I want to highlight some cells in my tableView. By highlighting I mean setting the background color of the cell to the blue color used for example when copying a text. I used tried this code to check if it works

public func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        cell.setHighlighted(true, animated: false)
    }

I also tried this

cell.setSelected(true, animated: false)

In both cases the cells become grey and not blue. Is there a solution for that?

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
J.Doe
  • 697
  • 2
  • 16
  • 26

2 Answers2

4

Change the selectionStyle property of yourcell. If you want to change it to UITableViewCellSelectionStyleBlue, it will be blue. for alternate method , you can get the another SO answer

for e.g

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.selectionStyle = .blue
}

UITableViewCell has three default selection styles:-

typedef NS_ENUM(NSInteger, UITableViewCellSelectionStyle) {
UITableViewCellSelectionStyleNone,
UITableViewCellSelectionStyleBlue,
UITableViewCellSelectionStyleGray,
UITableViewCellSelectionStyleDefault NS_ENUM_AVAILABLE_IOS(7_0)
};

or you can directly set the Selection color in your cell class like

enter image description here

Community
  • 1
  • 1
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
0

Try like this

 public func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        cell.selectionStyle = .blue
    }
Bhupat Bheda
  • 1,968
  • 1
  • 8
  • 13