gpt4 book ai didi

iphone - 突出显示时更改 UIButton 的背景颜色

转载 作者:行者123 更新时间:2023-12-03 18:16:49 26 4
gpt4 key购买 nike

嗨,我想更改用户点击按钮的 UIButton 背景颜色。

我使用渐变显示背景颜色,当用户点击时我需要更改渐变颜色。

[btn setTitle: @"Next" forState:UIControlStateNormal];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = btn.bounds;
gradient.cornerRadius = 10.0f;
locations = [[NSArray alloc] initWithObjects: 0.0f, 0.0f, 0.0f,0.0f, nil];
[gradient setLocations:locations];
colorNext = [[NSArray alloc] initWithObjects:…., nil];
gradient.colors = colorNext;
[locations release];
[btn.layer insertSublayer:gradient atIndex:0];
btn.titleLabel.textColor = [UIColor blackColor];

最佳答案

不建议更改 UIButton 的内部层层次结构,因为它可能会在将来的 iOS 更新中中断。此外,它还可能导致 Apple 拒绝您的申请。更好的解决方案是创建一个按钮子类。以下是如何执行此操作的示例:

@interface MyButton : UIButton
@end

@implementation MyButton

- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
[self addObserver:self forKeyPath:@"highlighted" options:NSKeyValueObservingOptionNew context:NULL];
}

return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
[self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];

if (self.highlighted == YES)
{
CGContextRef ctx = UIGraphicsGetCurrentContext();

CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();

const CGFloat *topGradientColorComponents = CGColorGetComponents([UIColor whiteColor].CGColor);
const CGFloat *bottomGradientColorComponents = CGColorGetComponents([UIColor blackColor].CGColor);

CGFloat colors[] =
{
topGradientColorComponents[0], topGradientColorComponents[1], topGradientColorComponents[2], topGradientColorComponents[3],
bottomGradientColorComponents[0], bottomGradientColorComponents[1], bottomGradientColorComponents[2], bottomGradientColorComponents[3]
};
CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors) / (sizeof(colors[0]) * 4));
CGColorSpaceRelease(rgb);

CGContextDrawLinearGradient(ctx, gradient, CGPointMake(0, 0), CGPointMake(0, self.bounds.size.height), 0);
CGGradientRelease(gradient);
}
else
{
// Do custom drawing for normal state
}
}

- (void)dealloc
{
[self removeObserver:self forKeyPath:@"highlighted"];

[super dealloc];
}

@end

您可能需要对其进行一些修改才能使其执行您想要的操作,但我认为您已经了解了基本的想法。

关于iphone - 突出显示时更改 UIButton 的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4022763/

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