1

I'm working with RESIDEMENU,and trying to add a line between cells of LeftMenuViewController,here is my code:

- (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];
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:21];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.highlightedTextColor = [UIColor lightGrayColor];
    cell.selectedBackgroundView = [[UIView alloc] init];
}

NSArray *titles = @[@"Home", @"Calendar", @"Profile", @"Settings", @"Log Out"];
NSArray *images = @[@"IconHome", @"IconCalendar", @"IconProfile", @"IconSettings", @"IconEmpty"];
cell.textLabel.text = titles[indexPath.row];
cell.imageView.image = [UIImage imageNamed:images[indexPath.row]];
UIView * lineView= [[UIView alloc]initWithFrame:CGRectMake(10, 0, cell.contentView.bounds.size.width, 3)];
lineView.backgroundColor=[UIColor redColor];

[cell.contentView addSubview:lineView];

return cell;
}

I can see these lines at first, but when I touch any cell, the cell is highlighted ,and the line of this cell disappear weirdly.any way to fix it?

snapshot before : enter image description here

snapshot when click a cell: enter image description here

wj2061
  • 6,778
  • 3
  • 36
  • 62

2 Answers2

2

UITableViewCell changes the background color of all sub views when cell is selected or highlighted.

You have three options :

  1. No selection style

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
  2. Subclass UITableViewCell and overriding Tableview cell's setSelected:animated and/or setHighlighted:animated

  3. Add the line as a layer

    CALayer* layer = [CALayer layer];
    layer.frame = CGRectMake(10, 0, cell.contentView.bounds.size.width, 3);
    layer.backgroundColor = [UIColor redColor].CGColor;
    [cell.contentView.layer  addSublayer:layer];
    
Alaeddine
  • 6,104
  • 3
  • 28
  • 45
0

Another workaround is overwriting setBackgroundColor: and expose similar method to change its backgroundColor.

@interface

- (void)setPersistentBackgroundColor:(UIColor*)color;

@implementation

- (void)setPersistentBackgroundColor:(UIColor*)color
{
    super.backgroundColor = color;
}

- (void)setBackgroundColor:(UIColor *)color
{
    // [super setBackgroundColor:color];
    // prohibit from changing its background color.
}
tounaobun
  • 14,570
  • 9
  • 53
  • 75