343

I have created a custom UITableViewCell. The table view is showing data fine. What I am stuck in is when user touches cell of tableview, then I want to show the background color of the cell other than the default [blue color] values for highlighting the selection of cell. I use this code but nothing happens:

cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];
sKhan
  • 9,694
  • 16
  • 55
  • 53
Mc.Lover
  • 4,813
  • 9
  • 46
  • 80

34 Answers34

703

No need for custom cells. If you only want to change the selected color of the cell, you can do this:

Objective-C:

UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];

Swift:

let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.red
cell.selectedBackgroundView = bgColorView
pkamb
  • 33,281
  • 23
  • 160
  • 191
Maciej Swic
  • 11,139
  • 8
  • 52
  • 68
  • 48
    This works, but in a grouped UITableView, the rounded corners are lost. – David Mar 24 '11 at 19:38
  • 1
    @David Does the cornerRadius = 7 work anywhere in the grouped table view? What if the cell is in the middle? Don't have time to test this. – Maciej Swic Jul 22 '13 at 08:15
  • Why is masksToBounds necessary? – Bradley Thomas Jan 29 '14 at 20:29
  • This is not working on OSX, saying : "NSView does not have a member named backgroundColor", anyone knows how to fix it ? – Alberto Jun 22 '14 at 17:32
  • 2
    for swift is little mistake. Correct line is cell.selectedBackgroundView = bgColorView – John Kakon Jun 26 '14 at 08:58
  • 15
    Be aware that for this to work, in the Storyboard (or XIB file) you must select a Selected Background colour other than None. This is contrary to some answers that say you first need to set it to None for it to work. With None, it won't work. Was driving me crazy till I figured it out. Thanks. – kakubei Dec 05 '14 at 16:37
  • 1
    How would you make this work when you are also using storyboard? – John Apr 15 '15 at 04:54
  • @MaciejSwic Is there any way to reduce the size of selection color.When i select the whole cell is selcted i want only the text part selected – Lydia May 28 '15 at 08:39
  • @Lyida What do you mean? You only want the background color of the text to change? – Maciej Swic May 28 '15 at 08:41
  • @MaciejSwic I have a customrized tableview cell.In left side i have a button also.When i select cell it hide that button also.Is there any way to reduce the size of the selection view. – Lydia May 28 '15 at 08:43
  • @Lyida Sounds like a view hierarchy issue, are both your label and button inside the cells contentView? You may want to post a separate question for this. – Maciej Swic May 28 '15 at 08:45
  • @Lyida Please post a new question with screenshots and code, then link it here. – Maciej Swic May 28 '15 at 08:46
  • @MaciejSwic http://stackoverflow.com/questions/30502189/tableview-selection-hides-my-button-within-the-tableview-cell Please take a look on it – Lydia May 28 '15 at 09:15
  • Using this solution with `UIAppearance` did not work properly for **iOS 7.2**. Thats why I needed to put same solution in `UITableViewCell` subclass and set the `backgroundColor` of the `selectedBackgroundView` in a custom `UIColor` property (with `UI_APPEARANCE_SELECTOR`) - and that works like a charm. Take a look at my [answer](http://stackoverflow.com/a/32208591/2471006) here. – anneblue Aug 26 '15 at 10:24
  • Adding issue in other subview's background color. – Mohammad Zaid Pathan Nov 21 '15 at 15:25
  • You can create an extension using @IBInspectable to make this available in XIBs and Storyboards. – chaingarden Mar 05 '18 at 04:37
  • This works fine, but why doesn't it work to set the `backgroundColor` of an existing (not nil) `selectedBackgroundView`??? – ndreisg Mar 21 '18 at 08:37
387

I think you were on the right track, but according to the class definition for selectedBackgroundView:

The default is nil for cells in plain-style tables (UITableViewStylePlain) and non-nil for section-group tables UITableViewStyleGrouped).

Therefore, if you're using a plain-style table, then you'll need to alloc-init a new UIView having your desired background colour and then assign it to selectedBackgroundView.

Alternatively, if all you wanted was a gray background when the cell is selected, you could use this:

cell.selectionStyle = UITableViewCellSelectionStyleGray;
starball
  • 20,030
  • 7
  • 43
  • 238
Andrew Little
  • 6,606
  • 1
  • 25
  • 15
  • 1
    This property can also be set in the storyboard if you prefer to leave view related stuff to the view. – IIllIIll Nov 13 '15 at 13:26
  • 1
    Swift 3 version : cell.selectionStyle = .gray // You can also use .none, .blue or .default – Sébastien REMY Jan 08 '17 at 20:48
  • 7
    This answer is quite old... Has there somehing been changed in newer iOS versions? I have a plain-style table and my selectedBackgroundView is NOT nil. Interestingly changing the backgroundColor on this view does not have any effect, instead i have to replace it by a new UIView with my desired backgroundColor to make it work. – ndreisg Mar 21 '18 at 08:18
  • You just saved me from going completely insane. Many thanks! – jbm Jan 12 '19 at 16:41
  • you can just _change_ the backgroundView's backgroundColor property like so: `cell.selectedBackgroundView?.backgroundColor = – fingia Jun 26 '20 at 22:26
52

Table View Cell selection background color can be set via the Storyboard in Interface Builder:

table view cell selection color None

pkamb
  • 33,281
  • 23
  • 160
  • 191
  • 1
    I think we cant set custom color from storyboard. Need to set it programatically. – pallavi Nov 05 '19 at 05:20
  • If you have multi-select during editing this is no good solution.. – Yaroslav Dukal Mar 25 '22 at 09:02
  • And did you indeed find a good solution? I'm fighting exaclty this right now. I want no selection background/stripe color. When I go into multiselect editing mode, i want to be able to see the checkmarks get selected, but not a color. I am killing myself trying to figure out the dart through configuration that makes this work. – Travis Griggs Sep 01 '22 at 22:38
37

If you have a grouped table with just one cell per section, just add this extra line to the code: bgColorView.layer.cornerRadius = 10;

UIView *bgColorView = [[UIView alloc] init];
[bgColorView setBackgroundColor:[UIColor redColor]];
bgColorView.layer.cornerRadius = 10;
[cell setSelectedBackgroundView:bgColorView];
[bgColorView release]; 

Don't forget to import QuartzCore.

Navnath Godse
  • 2,233
  • 2
  • 23
  • 32
Christian Fritz
  • 395
  • 4
  • 10
34

Swift 3: for me it worked when you put it in the cellForRowAtIndexPath: method

let view = UIView()
view.backgroundColor = UIColor.red
cell.selectedBackgroundView = view
UdayM
  • 1,725
  • 16
  • 34
phitsch
  • 823
  • 13
  • 12
22

The following works for me in iOS 8.

I have to set the selection style to UITableViewCellSelectionStyleDefault for custom background color to work. If any other style, the custom background color will be ignored. There seems to be a change in behaviours as previous answers needs to set style to none instead.

The full code for the cell as follows:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"MyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // This is how you change the background color
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    UIView *bgColorView = [[UIView alloc] init];
    bgColorView.backgroundColor = [UIColor redColor];
    [cell setSelectedBackgroundView:bgColorView];        
    return cell;
}
sKhan
  • 9,694
  • 16
  • 55
  • 53
samwize
  • 25,675
  • 15
  • 141
  • 186
  • This code is leaking memory. Any "alloc" or object creation must be in if (cell ==nil) { } block. Or the view will be created everytime the cell is released by iOS. – GeneCode Feb 12 '16 at 04:24
18

Create a custom cell for your table cell and in the custom cell class.m put the code below, it will work fine. You need to place the desired color image in selectionBackground UIImage.

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    UIImage *selectionBackground = [UIImage imageNamed:@"yellow_bar.png"];
    UIImageView *iview=[[UIImageView alloc] initWithImage:selectionBackground];
    self.selectedBackgroundView=iview;
}
rajesh
  • 592
  • 4
  • 13
  • 2
    I think this could be more memory efficient than setting a selectedBackgroundView when initializing the cell by only creating the bg view when one cell is selected. – dotslashlu Aug 02 '13 at 14:10
12

Swift 3.0 extension

extension UITableViewCell {
    var selectionColor: UIColor {
        set {
            let view = UIView()
            view.backgroundColor = newValue
            self.selectedBackgroundView = view
        }
        get {
            return self.selectedBackgroundView?.backgroundColor ?? UIColor.clear
        }
    }
}

cell.selectionColor = UIColor.FormaCar.blue

Community
  • 1
  • 1
Nike Kov
  • 12,630
  • 8
  • 75
  • 122
10

In Swift 4, you can also set the background color of your table cell globally (taken from here):

let backgroundColorView = UIView()
backgroundColorView.backgroundColor = UIColor.red
UITableViewCell.appearance().selectedBackgroundView = backgroundColorView
sundance
  • 2,930
  • 1
  • 20
  • 25
9
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIView *view = [[UIView alloc] init];
    [view setBackgroundColor:[UIColor redColor]];
    [cell setSelectedBackgroundView:view];
}

We need to set the selected background view in this method.

P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
Hemanshu Liya
  • 611
  • 6
  • 10
9

Swift 4+:

Add following lines in your table cell

let bgColorView = UIView()
bgColorView.backgroundColor =  .red
self.selectedBackgroundView = bgColorView

Finally it should be as below

override func setSelected(_ selected: Bool, animated: Bool)
    {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
        let bgColorView = UIView()
        bgColorView.backgroundColor =  .red
        self.selectedBackgroundView = bgColorView

    }
Rajesh Loganathan
  • 11,129
  • 4
  • 78
  • 90
8

If you want to add a custom highlighted color to your cell (and your cell contains buttons,labels, images,etc..) I followed the next steps:

For example if you want a selected yellow color:

1) Create a view that fits all the cell with 20% opacity (with yellow color) called for example backgroundselectedView

2) In the cell controller write this:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
     self.backgroundselectedView.alpha=1;
    [super touchesBegan:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.backgroundselectedView.alpha=0;
    [super touchesEnded:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.backgroundSelectedImage.alpha=0;
    [super touchesCancelled:touches withEvent:event];
}
Javier Flores Font
  • 2,075
  • 15
  • 13
6

If you are using a custom TableViewCell, you can also override awakeFromNib:

override func awakeFromNib() {
    super.awakeFromNib()

    // Set background color
    let view = UIView()
    view.backgroundColor = UIColor.redColor()
    selectedBackgroundView = view
}
Quanlong
  • 24,028
  • 16
  • 69
  • 79
Franck
  • 8,939
  • 8
  • 39
  • 57
5

One more tip to Christian's way to show rounded corner background for grouped table.

If I use cornerRadius = 10 for cell, it shows four corner's rounded selection background. It's not the same with table view's default UI.

So, I think about easy way to resolve it with cornerRadius. As you can see from the below codes, check about cell's location (top, bottom, middle or topbottom) and add one more sub layers to hide top corner or bottom corner. This just shows exactly same look with default table view's selection background.

I tested this code with iPad splitterview. You can change patchLayer's frame position as you needed.

Please let me know if there is more easier way to achieve same result.

if (tableView.style == UITableViewStyleGrouped) 
{
    if (indexPath.row == 0) 
    {
        cellPosition = CellGroupPositionAtTop;
    }    
    else 
    {
        cellPosition = CellGroupPositionAtMiddle;
    }

    NSInteger numberOfRows = [tableView numberOfRowsInSection:indexPath.section];
    if (indexPath.row == numberOfRows - 1) 
    {
        if (cellPosition == CellGroupPositionAtTop) 
        {
            cellPosition = CellGroupPositionAtTopAndBottom;
        } 
        else 
        {
            cellPosition = CellGroupPositionAtBottom;
        }
    }

    if (cellPosition != CellGroupPositionAtMiddle) 
    {
        bgColorView.layer.cornerRadius = 10;
        CALayer *patchLayer;
        if (cellPosition == CellGroupPositionAtTop) 
        {
            patchLayer = [CALayer layer];
            patchLayer.frame = CGRectMake(0, 10, 302, 35);
            patchLayer.backgroundColor = YOUR_BACKGROUND_COLOR;
            [bgColorView.layer addSublayer:patchLayer];
        } 
        else if (cellPosition == CellGroupPositionAtBottom) 
        {
            patchLayer = [CALayer layer];
            patchLayer.frame = CGRectMake(0, 0, 302, 35);
            patchLayer.backgroundColor = YOUR_BACKGROUND_COLOR;
            [bgColorView.layer addSublayer:patchLayer];
        }
    }
}
Rishil Patel
  • 1,977
  • 3
  • 14
  • 30
Wonil
  • 6,364
  • 2
  • 37
  • 55
5

I want to note that the XIB editor offers you the following standard options:

Section: blue/gray/none

(the right-hand column with options, 4th tab, first group "Table View Cell", 4th subgroup, the 1st of 3 items reads "Selection")

Probably what you want to do may be achieved by selecting the right standard option.

18446744073709551615
  • 16,368
  • 4
  • 94
  • 127
  • you're right. Due to, if you do so you can simple change the selection color in "cellForRowAtIndexPath" by adding: UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; cell.selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectZero]; cell.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:(255/255) green:(0/255) blue:(0/255) alpha:0.1]; – user8675 Feb 10 '15 at 21:51
3

As per custom color for a selected cell in UITableView, great solution as per Maciej Swic's answer

Just to add to that, you declare Swic's answer in the Cell configuration usually under:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

And for an added effect, instead of the system colors, you may use RGB values for a custom color look. In my code this is how I achieved it:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

} 

 static NSString *CellIdentifier = @"YourCustomCellName";
 MakanTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

// Configure the cell...

if (cell == nil) {

cell = [[[NSBundle mainBundle]loadNibNamed:@"YourCustomCellClassName" owner:self options:nil]objectAtIndex:0];
                    } 

UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor colorWithRed:255.0/256.0 green:239.0/256.0 blue:49.0/256.0 alpha:1];
bgColorView.layer.cornerRadius = 7;
bgColorView.layer.masksToBounds = YES;
[cell setSelectedBackgroundView:bgColorView];


return cell;

}

Let me know if that works for you as well. You can mess with the cornerRadius number for the effects on the corners of the selected cell.

Community
  • 1
  • 1
DrBongo
  • 49
  • 6
3

To add the background for all cells (using Maciej's answer):

for (int section = 0; section < [self.tableView numberOfSections]; section++) {
        for (int row = 0; row < [self.tableView numberOfRowsInSection:section]; row++) {
            NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:section];
            UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:cellPath];

            //stuff to do with each cell
            UIView *bgColorView = [[UIView alloc] init];
            bgColorView.backgroundColor = [UIColor redColor];
            [cell setSelectedBackgroundView:bgColorView];
        }
    } 
John
  • 1,677
  • 4
  • 15
  • 26
2

I've got a slightly different approach than everyone else that reflects the selection on touch rather than after being selected. I have a subclassed UITableViewCell. All you have to do is set the background color in the touch events, which simulates selection on touch, and then set the background color in the setSelected function. Setting the background color in the selSelected function allows for deselecting the cell. Make sure to pass the touch event to the super, otherwise the cell won't actually act as if its selected.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    self.backgroundColor = UIColor(white: 0.0, alpha: 0.1)
    super.touchesBegan(touches, withEvent: event)
}

override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
    self.backgroundColor = UIColor.clearColor()
    super.touchesCancelled(touches, withEvent: event)
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
    self.backgroundColor = selected ? UIColor(white: 0.0, alpha: 0.1) : UIColor.clearColor()
}
Stephen Donnell
  • 810
  • 9
  • 20
2

To override UITableViewCell's setSelected also works.

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Set background color
    let view = UIView()
    view.backgroundColor = UIColor.redColor()
    selectedBackgroundView = view
}
Quanlong
  • 24,028
  • 16
  • 69
  • 79
2

for those that just want to get rid of the default selected grey background put this line of code in your cellForRowAtIndexPath func:

yourCell.selectionStyle = .None
Paul Lehn
  • 3,202
  • 1
  • 24
  • 29
2

for Swift 3.0:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = super.tableView(tableView, cellForRowAt: indexPath)

    cell.contentView.backgroundColor = UIColor.red
}
Wilson
  • 9,006
  • 3
  • 42
  • 46
2

I use below approach and works fine for me,

class MyTableViewCell : UITableViewCell {

                var defaultStateColor:UIColor?
                var hitStateColor:UIColor?

                 override func awakeFromNib(){
                     super.awakeFromNib()
                     self.selectionStyle = .None
                 }

// if you are overriding init you should set selectionStyle = .None

                override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
                    if let hitColor = hitStateColor {
                        self.contentView.backgroundColor = hitColor
                    }
                }

                override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
                    if let defaultColor = defaultStateColor {
                        self.contentView.backgroundColor = defaultColor
                    }
                }

                override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
                    if let defaultColor = defaultStateColor {
                        self.contentView.backgroundColor = defaultColor
                    }
                }
            }
Suryavel TR
  • 3,576
  • 1
  • 22
  • 25
2

1- Add a view to the content view of your cell.
2- Right click your cell.
3- Make the added view as "selectedBackgroundView".

enter image description here

fullmoon
  • 8,030
  • 5
  • 43
  • 58
1

Here is the important parts of the code needed for a grouped table. When any of the cells in a section are selected the first row changes color. Without initially setting the cellselectionstyle to none there is an annonying double reload when the user clicks row0 where the cell changes to bgColorView then fades and reloads bgColorView again. Good Luck and let me know if there is a simpler way to do this.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    if ([indexPath row] == 0) 
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UIView *bgColorView = [[UIView alloc] init];
        bgColorView.layer.cornerRadius = 7;
        bgColorView.layer.masksToBounds = YES;
        [bgColorView setBackgroundColor:[UIColor colorWithRed:.85 green:0 blue:0 alpha:1]];
        [cell setSelectedBackgroundView:bgColorView];

        UIColor *backColor = [UIColor colorWithRed:0 green:0 blue:1 alpha:1];
        cell.backgroundColor = backColor;
        UIColor *foreColor = [UIColor colorWithWhite:1 alpha:1];
        cell.textLabel.textColor = foreColor;

        cell.textLabel.text = @"row0";
    }
    else if ([indexPath row] == 1) 
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UIColor *backColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
        cell.backgroundColor = backColor;
        UIColor *foreColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
        cell.textLabel.textColor = foreColor;

        cell.textLabel.text = @"row1";
    }
    else if ([indexPath row] == 2) 
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UIColor *backColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
        cell.backgroundColor = backColor;
        UIColor *foreColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
        cell.textLabel.textColor = foreColor;

        cell.textLabel.text = @"row2";
    }
    return cell;
}

#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:[indexPath section]];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:path];
    [cell setSelectionStyle:UITableViewCellSelectionStyleBlue];

    [tableView selectRowAtIndexPath:path animated:YES scrollPosition:UITableViewScrollPositionNone];

}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tvStat cellForRowAtIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}

#pragma mark Table view Gestures

-(IBAction)singleTapFrom:(UIGestureRecognizer *)tapRecog
{

    CGPoint tapLoc = [tapRecog locationInView:tvStat];
    NSIndexPath *tapPath = [tvStat indexPathForRowAtPoint:tapLoc];

    NSIndexPath *seleRow = [tvStat indexPathForSelectedRow];
    if([seleRow section] != [tapPath section])
        [self tableView:tvStat didDeselectRowAtIndexPath:seleRow];
    else if (seleRow == nil )
        {}
    else if([seleRow section] == [tapPath section] || [seleRow length] != 0)
        return;

    if(!tapPath)
        [self.view endEditing:YES];

    [self tableView:tvStat didSelectRowAtIndexPath:tapPath];
}
firescar96
  • 419
  • 3
  • 8
1
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];

Make sure you have used the above line to use the selection effect

Hemang
  • 26,840
  • 19
  • 119
  • 186
tushar
  • 85
  • 1
  • 1
  • 5
1
override func setSelected(selected: Bool, animated: Bool) {
    // Configure the view for the selected state

    super.setSelected(selected, animated: animated)
    let selView = UIView()

    selView.backgroundColor = UIColor( red: 5/255, green: 159/255, blue:223/255, alpha: 1.0 )
    self.selectedBackgroundView = selView
}
Ranjan
  • 95
  • 9
1

In case of custom cell class. Just override:

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state

    if (selected) {
        [self setBackgroundColor: CELL_SELECTED_BG_COLOR];
        [self.contentView setBackgroundColor: CELL_SELECTED_BG_COLOR];
    }else{
        [self setBackgroundColor: [UIColor clearColor]];
        [self.contentView setBackgroundColor: [UIColor clearColor]];
    }
}
Lal Krishna
  • 15,485
  • 6
  • 64
  • 84
0

It's easy when the table view style is plain, but in group style, it's a little trouble, I solve it by:

CGFloat cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kGroupTableViewCellWidth+2, cellHeight)];
view.backgroundColor = kCommonHighlightedColor;
cell.selectedBackgroundView = view;
[view release];
UIRectCorner cornerFlag = 0;
CGSize radii = CGSizeMake(0, 0);
NSInteger theLastRow = --> (yourDataSourceArray.count - 1);
if (indexPath.row == 0) {
    cornerFlag = UIRectCornerTopLeft | UIRectCornerTopRight;
    radii = CGSizeMake(10, 10);
} else if (indexPath.row == theLastRow) {
    cornerFlag = UIRectCornerBottomLeft | UIRectCornerBottomRight;
    radii = CGSizeMake(10, 10);
}
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:cornerFlag cornerRadii:radii];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = maskPath.CGPath;
view.layer.mask = shapeLayer;

noted the kGroupTableViewCellWidth, I define it as 300, it's the width of group table view cell width in iPhone

勇敢的心
  • 341
  • 2
  • 4
0

I'm using iOS 9.3 and setting the color through the Storyboard or setting cell.selectionStyle didn't work for me, but the code below worked:

UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:55 / 255.0 
                                                  green:141 / 255.0 
                                                   blue:211 / 255.0 
                                                  alpha:1.0];
cell.selectedBackgroundView = customColorView;

return cell;

I found this solution here.

Felipe Andrade
  • 509
  • 6
  • 23
0

Try Following code.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[cellIdArray objectAtIndex:indexPath.row] forIndexPath:indexPath];

    // Configure the cell...
    cell.backgroundView =
    [[UIImageView alloc] init] ;
    cell.selectedBackgroundView =[[UIImageView alloc] init];

    UIImage *rowBackground;
    UIImage *selectionBackground;


    rowBackground = [UIImage imageNamed:@"cellBackgroundDarkGrey.png"];
    selectionBackground = [UIImage imageNamed:@"selectedMenu.png"];

    ((UIImageView *)cell.backgroundView).image = rowBackground;
    ((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;



    return cell;
}

//Swift Version:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell


        cell.selectedBackgroundView = UIImageView()
        cell.backgroundView=UIImageView()

        let selectedBackground : UIImageView = cell.selectedBackgroundView as! UIImageView
        selectedBackground.image = UIImage.init(named:"selected.png");

        let backGround : UIImageView = cell.backgroundView as! UIImageView
        backGround.image = UIImage.init(named:"defaultimage.png");

        return cell


    } 
Avijit Nagare
  • 8,482
  • 7
  • 39
  • 68
0

Swift 4.x

To Change the selection background Colour to anyColour use Swift Extension

Create UITableView Cell extension as below

extension UITableViewCell{

    func removeCellSelectionColour(){
        let clearView = UIView()
        clearView.backgroundColor = UIColor.clear
        UITableViewCell.appearance().selectedBackgroundView = clearView
    } 

}

Then call removeCellSelectionColour() with cell instance.

iSrinivasan27
  • 1,406
  • 1
  • 21
  • 28
-1

Swift 5 - Xcode version 12.1 (12A7403)

|Step One|
Add the following to your AppDelegate.swift file

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let colorView = UIView()
    colorView.backgroundColor = UIColor.lightGray

    UITableViewCell.appearance().selectedBackgroundView = colorView
        
    return true
}

|Step Two|
Make sure your cell's Content View background is set to "Clear Color" (and not "Default") in the Attributes Inspector. This is done to not conflict with your App Delegate setting.

koen
  • 5,383
  • 7
  • 50
  • 89
-2
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView reloadData];
    UITableViewCell *cell=(UITableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    [cell setBackgroundColor:[UIColor orangeColor]];
}
-8

Use [cell setClipsToBounds:YES]; for Grouped style cell

DD_
  • 7,230
  • 11
  • 38
  • 59
kevin.ng
  • 67
  • 7