带有GradientLayer的UIButton会遮挡图像并使渐变变暗

时间:2011-11-12 18:37:21

标签: ios uibutton calayer cagradientlayer

我在这里有一个UIButton,我想在图像下面有一个渐变作为背景(带有透明背景的符号),但我面临着两个不同的问题。

无论我如何尝试添加它,CAGradientLayer的第一个似乎都叠加在图像的顶部,完全遮盖了图像。

其次,渐变本身似乎变暗了很多,就像按钮被禁用一样,但事实并非如此。

这是我的代码:

self.backButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 35, 28, 28)];
[backButton addTarget:self
               action:@selector(goBack)
     forControlEvents:UIControlEventTouchUpInside];
[backButton setBackgroundColor:[UIColor clearColor]];
CAGradientLayer *buttonGradient = [CAGradientLayer layer];
buttonGradient.frame = backButton.bounds;
buttonGradient.colors = [NSArray arrayWithObjects:
                         (id)[[UIColor colorWithRed:.0
                                              green:.166
                                               blue:.255
                                              alpha:1] CGColor], 
                         (id)[[UIColor colorWithRed:.0
                                              green:.113
                                               blue:.255
                                              alpha:1] CGColor], 
                         nil];
[buttonGradient setCornerRadius:backButton.frame.size.width / 2];
[backButton.layer insertSublayer:buttonGradient
                         atIndex:0];
[backButton setImage:[UIImage imageNamed:@"backarrow.png"]
            forState:UIControlStateNormal];
[backButton setEnabled:NO];
[topbarView addSubview:backButton];

4 个答案:

答案 0 :(得分:70)

所以我设法通过在添加渐变后执行[button bringSubviewToFront:button.imageView]来解决这个问题。似乎无论我做什么,新图层都会添加到imageView的顶部,所以我需要将其推到前面。

<强>目标-C:

[button bringSubviewToFront:button.imageView] 

Swift 4.1:

button.bringSubview(toFront:button.imageView!)

答案 1 :(得分:27)

或者,您可以在图像视图的图层下面插入渐变图层

CAGradientLayer* gradient = [CAGradientLayer layer];
// ...
[button.layer insertSublayer:gradient below:button.imageView.layer];

答案 2 :(得分:4)

SWIFT 3

这是一个例子:(基于Neil回答)

    let layer = CAGradientLayer()
    layer.frame = CGRect(x: 0, y: 0, width: myButtonOutlet.layer.frame.size.width, height: myButtonOutlet..layer.frame.size.height)
    layer.colors = [UIColor.white.cgColor, pixelColorReceta.cgColor]
    layer.masksToBounds = true
    layer.cornerRadius = myButtonOutlet.layer.cornerRadius
    myButtonOutlet.layer.insertSublayer(layer, below: myButtonOutlet..imageView?.layer)

快乐编码:)

答案 3 :(得分:-1)

Swift 3

您可以将图像移动到渐变上方:

button.imageView?.layer.zPosition = 1

或在图像下插入渐变:

button.layer.insertSublayer(gradientLayer, below: button.imageView?.layer)