【问题标题】:How to add CAGradientLayer to UIButton如何将 CAGradientLayer 添加到 UIButton
【发布时间】:2012-12-28 18:44:52
【问题描述】:

我正在尝试修改按钮的外观并花了很长时间试图弄清楚为什么我不能像下面这个简单的代码那样对其应用渐变:

[self.playButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
self.playButton.backgroundColor = [UIColor blackColor];

CAGradientLayer *gradient = [[CAGradientLayer alloc] init];
gradient.frame = self.playButton.bounds;
gradient.position = CGPointMake(self.playButton.bounds.size.width/2, self.playButton.bounds.size.height/2);
gradient.colors = [NSArray arrayWithObjects:
                   (id)[UIColor greenColor].CGColor,
                   (id)[UIColor redColor].CGColor,
                   nil];
gradient.locations = [NSArray arrayWithObjects:
                      [NSNumber numberWithFloat:0.0f],
                      [NSNumber numberWithFloat:1.0f],
                      nil];

[self.playButton.layer addSublayer:gradient];

它执行,但没有任何反应。我知道代码应该可以工作,因为许多其他人都在使用它,并且当将 self.playButton 更改为 self.view 时,它会为 UIView 添加一个漂亮的红绿色渐变层。

可能值得注意的是,我将自定义按钮定义为IBOutlet,如下所示:

@property (weak, nonatomic) IBOutlet UIButton *playButton;

非常感谢任何帮助。

更新和修复

将按钮更改为使用可缩放图像而不是渐变时,我忘记重新注释掉渐变代码(在尝试rokjarc 的想法之后)以及将按钮的imageView.content 更改为UIViewContentModeScaleToFill显示的渐变...

self.playButton.imageView.contentMode = UIViewContentModeScaleToFill;

所以谢谢rokjarc 我想:D

【问题讨论】:

    标签: ios uibutton cagradientlayer


    【解决方案1】:

    简单的改变

    self.playButton.backgroundColor = [UIColor blackColor];
    

    self.playButton.backgroundColor = [UIColor clearColor];
    

    刚刚测试过,它可以工作。

    【讨论】:

    • 也试过了,但这也不起作用。我想应用下面链接中解释的渐变,但由于光泽渐变和我的红绿色渐变显示都没有我真的迷路了。 stackoverflow.com/questions/6936917/…
    • 似乎imageView.content 模式设置不正确。将其更改为UIViewContentModeScaleToFill,现在它可以工作了:o
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多