有没有办法在界面构建器中制作渐变背景颜色? [英] Is there a way to make gradient background color in the interface builder?

查看:55
本文介绍了有没有办法在界面构建器中制作渐变背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的应用程序,我正在使用TableView和自定义的UITableViewCells.

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 also make the background color of my customized cell a gradient in the interface builder?

谢谢.

推荐答案

要绘制渐变,您将必须继承子类并以编程方式覆盖drawRect:

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);
}

最简单的方法保留在界面生成器中的方法可能是对UIView进行子类化,以使其在drawRect中绘制渐变并将其放置在其他子视图后面的单元格中:

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

但是,最好的方法可能不是为此使用接口构建器,而是创建UITableViewCell的子类.对于高级定制,界面构建器往往只会使我的经历变得更复杂.不过,这取决于个人喜好.

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.

这篇关于有没有办法在界面构建器中制作渐变背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆