UIButton渐变不起作用 [英] UIButton gradient not working

查看:443
本文介绍了UIButton渐变不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从教程中找到了这段代码并尝试使用它:

I found this code from tutorial and tried to use it:

CAGradientLayer *btnGradient = [CAGradientLayer layer];
btnGradient.frame = button.bounds;
btnGradient.colors = [NSArray arrayWithObjects:
                      (id)[[UIColor colorWithRed:102.0f / 255.0f green:102.0f / 255.0f blue:102.0f / 255.0f alpha:1.0f] CGColor],
                      (id)[[UIColor colorWithRed:51.0f / 255.0f green:51.0f / 255.0f blue:51.0f / 255.0f alpha:1.0f] CGColor],
                      nil];
[button.layer insertSublayer:btnGradient atIndex:0];

代码在viewDidLoad方法中。

The code is in viewDidLoad method.

按钮在.h文件中定义如下: @property(非原子,强)IBOutlet UIButton *按钮;

button is defined like this in .h file: @property (nonatomic, strong) IBOutlet UIButton *button;

它在.m文件中的@synthesized并且它在界面构建器中连接

and it's @synthesized in .m file and it's connected in interface builder

我可以对按钮进行其他自定义,例如更改其背景颜色(纯色)和改变文字的颜色。但是当我尝试使用渐变色时,背景就是透明的。

I am able to do other customization to the button like changing its background color (solid color) and changing the color of text. But when I try to use gradient color the background is just transparent.

感谢您的帮助!

推荐答案

可能首先你需要设置框架按钮。试试这个。

Probably first you need to set the frame button. Try this.

+ (UIButton*) buttonWithGradient:(CGSize)size beginColor:(UIColor*)beginColor endColor:(UIColor*)endColor
{
    CGRect frame = { CGPointZero, size };

    UIButton* button = [[UIButton alloc] initWithFrame:frame];

    CAGradientLayer* gradient = [CAGradientLayer layer];
    gradient.frame = frame;
    gradient.colors = @[(id)beginColor.CGColor, (id)endColor.CGColor];
    [button.layer insertSublayer:gradient atIndex:0];

    return [button autorelease];
}

这篇关于UIButton渐变不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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