UITableViewCell with custom gradient background, with another gradient as highlight color

前端 未结 3 789
庸人自扰
庸人自扰 2020-12-08 06:29

I have a custom UITableViewCell with a custom layout. I wanted a gradient background, so in my UITableViewDelegate cellForRowAtIndexPath: method, I create a CAGradientLayer

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 06:54

    I struggled for days with this. The solution ended up being quite simple but the various parts of the puzzle were spread across several different answers and sites. The missing piece of the puzzle turned out to be the distinction between the content view and the background view and where the selection color is applied.

    Features of my solution:

    • I load my cell from a nib so that I can layout the content in IB. Feel free to lay out the content programmatically.
    • I grab the gradient colors from a global style object because I need to customize the gradient by client.
      • I set the selection color of the cell to gray in the nib so the default (blue) does not clash with my color scheme.
    • I add the gradients to the background view. If you don't do this, the selection color does not show correctly. UITableViewCell does not have a background view by default so you have to create it first.

    This last point was the secret ingredient that made it all work for me.

    I added a factory method to my UITableCellView subclass because I wanted to use the same cell in multiple tables.

    +(ActivityDetailCellView *) createWithStyle: (WMStyle *) style {  
      UIViewController *temporaryController = [[UIViewController alloc] 
           initWithNibName: @"ActivityDetailCellView"
           bundle: nil];
    
      ActivityDetailCellView *cell = (ActivityDetailCellView *) temporaryController.view;
    
      CAGradientLayer *lightGradient = [CAGradientLayer layer];
      lightGradient.frame = cell.bounds;
      lightGradient.colors = style.lightGradient;
    
      UIView *background = [[UIView alloc] initWithFrame: cell.bounds];
      [background.layer insertSublayer:lightGradient atIndex:0];  
      cell.backgroundView = background;
    
      return cell;
    }
    

提交回复
热议问题