带有GradientLayer的UIButton会遮挡图像并使渐变变暗 [英] UIButton with GradientLayer obscures image and darkens gradient

查看:985
本文介绍了带有GradientLayer的UIButton会遮挡图像并使渐变变暗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an UIButton here where I'd like to have a gradient as the background below the image (symbol with transparent background), but I'm facing two different problems.

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

First of the CAGradientLayer seems to overlay on top of the image no matter how I try to add it, obscuring the image completely.

其次渐变本身似乎它被暗化了很多,就像按钮被禁用一样,它不是。

Secondly the gradient itself seems to be darkened a lot, like the button was disabled, which it isn't.

这是我的代码:

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


推荐答案

所以我设法绕过这个做了[按钮bringSubviewToFront:button.imageView]添加渐变后。似乎无论我做什么,新图层都会添加到imageView之上,所以我需要将其推到前面。

So I managed to get around this by doing a [button bringSubviewToFront:button.imageView] after adding the gradient. Seems that no matter what I do the new layer will add on top of the imageView, so I need to push that to the front afterwards.

Objective-C :

[button bringSubviewToFront:button.imageView] 

Swift 4.1:

button.bringSubview(toFront:button.imageView!)

这篇关于带有GradientLayer的UIButton会遮挡图像并使渐变变暗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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