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

时间:2010-10-26 10:26:33

标签: iphone uibutton

您好我想更改用户点按按钮的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];

6 个答案:

答案 0 :(得分:36)

建议不要更改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

您可能需要对其进行一些修改才能使其达到您想要的效果,但我认为您已经掌握了基本想法。

答案 1 :(得分:31)

试试这个:

[Button addTarget:self action:@selector(doSomething:) forControlEvents:UIControlEventTouchUpInside];
[Button addTarget:self action:@selector(setBgColorForButton:) forControlEvents:UIControlEventTouchDown];
[Button addTarget:self action:@selector(clearBgColorForButton:) forControlEvents:UIControlEventTouchDragExit];

-(void)setBgColorForButton:(UIButton*)sender
{
    [sender setBackgroundColor:[UIColor blackColor]];
}

-(void)clearBgColorForButton:(UIButton*)sender
{
    [sender setBackgroundColor:[UIColor redColor]];
}

-(void)doSomething:(UIButton*)sender
{
double delayInSeconds = 0.3;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [sender setBackgroundColor:[UIColor redColor]];
    });
    //do something

}

答案 2 :(得分:25)

您可以使用此方法创建并固定指定颜色的UIImage,然后将其应用于按钮。我为UIImage做了一个类别来做这件事。

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, (CGRect){.size = size});

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

+ (UIImage *)imageWithColor:(UIColor *)color
{
    return [UIImage imageWithColor:color size:CGSizeMake(1, 1)];
}

用法:

[button setBackgroundImage:[UIImage imageWithColor:[UIColor redColor]]
                  forState:UIControlStateNormal];

正如Matthias指出的那样,您可以安全地使用1x1图像作为按钮背景 - 它将被拉伸以填充按钮。

答案 3 :(得分:5)

我在GitHub上找到了这个AYUIButton,它完美地工作了:) 以下是示例代码:

[btn setBackgroundColor:[UIColor redColor] forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor blueColor] forState:UIControlStateHighlighted];

答案 4 :(得分:2)

当您设置按钮的TintColor时,它会突出显示

[YourButton setTintColor:[UIColor color]];

答案 5 :(得分:0)

夫特

UIButton的扩展,允许您为每个州指定背景颜色:

https://github.com/acani/UIButtonBackgroundColor

请注意,对于iphone 6 plus,您应该在.swift类的扩展名内更改以下内容,以便为所有版本修复它:

//let rect = CGRect(x: 0, y: 0, width: 0.5, height: 0.5) comment this line
    let rect = CGRect(x: 0, y: 0, width: 1, height: 1)