Subview of UITableViewcell disappear when UItableViewcell is highlighted,anyway to fix it?

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

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 :

snapshot when click a cell:

回答1:

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];


回答2:

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. }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!