Is there a way to make gradient background color in the interface builder?

前端 未结 9 1146
终归单人心
终归单人心 2021-01-30 13:08

For my application I\'m using a TableView and using customized UITableViewCells.

I customized my cells via interface builder, not programmatically. Is there a way to als

9条回答
  •  伪装坚强ぢ
    2021-01-30 13:49

    To draw a gradient, you will have to subclass and override the drawRect programmatically:

    - (void)drawRect:(CGRect)rect
    {
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        CGContextSaveGState(context);
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGGradientRef gradient = CGGradientCreateWithColorComponents
                                 (colorSpace,
                                  (const CGFloat[8]){1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f},
                                  (const CGFloat[2]){0.0f,1.0f},
                                  2);
    
        CGContextDrawLinearGradient(context,
                                    gradient,
                                    CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMinY(self.bounds)),
                                    CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMaxY(self.bounds)),
                                    0);
    
        CGColorSpaceRelease(colorSpace);
        CGContextRestoreGState(context);
    }
    

    The easiest way, which keeps your cells in the interface builder, is probably to subclass a UIView to have it draw a gradient in its drawRect and place it in your cell behind the other subviews:

    GradientView *gradientView = [[GradientView alloc] init];
    gradientView.frame = cell.bounds;
    [cell addSubview:gradientView];
    [cell sendSubviewToBack:gradientView];
    

    However, the best way to do it is probably not to use the interface builder for this and make a subclass of UITableViewCell. For advanced customization, interface builders tend to only make things more complicated in my experience. That's up to personal preference though.

提交回复
热议问题