gpt4 book ai didi

iOS 在带有图像的 UIButton 下设置 CAGradientLayer

转载 作者:行者123 更新时间:2023-11-28 18:54:06 30 4
gpt4 key购买 nike

在我的 iOS 应用程序中我有一个问题,有一个带有图像的按钮,我想在图像下为按钮设置一个渐变,我写了这段代码:

- (void)viewDidLoad {
[super viewDidLoad];

CAGradientLayer *gradient = [GradientColor btnGreyGradient];
[gradient setFrame:self.btnTicketView.layer.bounds];
gradient.masksToBounds = YES;

[self.btnTicketView.layer insertSublayer:gradient atIndex:0];
self.btnTicketView.clipsToBounds = YES;
}

我的 GradientColor 类是:

 #import "GradientColor.h"

@implementation GradientColor


+(CAGradientLayer *)btnGreyGradient
{


UIColor *startColor = [UIColor colorWithRed:169.0/255.0 green:169.0/255.0 blue:169.0/255.0 alpha:1.0];
UIColor *endColor = [UIColor colorWithRed:128.0/255.0 green:128.0/255.0 blue:128.0/255.0 alpha:1.0];


NSArray *arrayColors = [NSArray arrayWithObjects:(id) startColor.CGColor, endColor.CGColor, nil];


CAGradientLayer *viewGradient = [CAGradientLayer layer];
viewGradient.colors = arrayColors;

return viewGradient;

}

问题是当我为我的按钮设置渐变时,我在 InterfaceBuilder 中设置的图像被覆盖了。我该如何解决这个问题??谢谢你

最佳答案

插入图层后将 imageView 置于顶部。

[self.btnTicketView.layer insertSublayer:gradient atIndex:0];
[self.btnTicketView bringSubviewToFront:self.btnTicketView.imageView];

编辑:

您可能想创建按钮的子类,以便可以重用,例如:

- (id)init
{
self = [super init];
if (self) {
[self myInit];
}
return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[self myInit];
}
return self;
}

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self myInit];
}
return self;
}

- (void) myInit
{
_gradientLayer = [[CAGradientLayer alloc] init];
_gradientLayer.frame = self.layer.bounds;

NSArray* locations = [NSArray arrayWithObjects:@0, @0.40, @0.60, @1, nil];

[_gradientLayer setLocations:locations];

[self.layer insertSublayer:_gradientLayer atIndex:0];

[self bringSubviewToFront:self.imageView];

NSArray* colors = [self getGradientColors];

[_gradientLayer setColors:colors];
}

关于iOS 在带有图像的 UIButton 下设置 CAGradientLayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36067877/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com