4

I am trying to create a UIButton with a gradient background. I got that work fine but the button does not highlight (default behavior is for the button to darken) when selected.

here's my button:

-(UIButton *)createLoginButtonForSize:(CGSize)size {
    UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    loginButton.translatesAutoresizingMaskIntoConstraints = FALSE;
    loginButton.layer.cornerRadius = 8;
    loginButton.titleLabel.text = @"Login";

    [loginButton addTarget:self action:@selector(loginCheck:) forControlEvents:UIControlEventTouchUpInside];


    [loginButton addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[loginButton(WIDTH)]"
                                                                        options:0
                                                                        metrics:@{@"WIDTH": [NSNumber numberWithFloat:size.width]}
                                                                          views:NSDictionaryOfVariableBindings(loginButton)]];

    [loginButton addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[loginButton(HEIGHT)]"
                                                                        options:0
                                                                        metrics:@{@"HEIGHT": [NSNumber numberWithFloat:size.height]}
                                                                          views:NSDictionaryOfVariableBindings(loginButton)]];

    CAGradientLayer *layer = [UIColor greenGradient];
    layer.frame = CGRectMake(0, 0, size.width, size.height);
    layer.cornerRadius = 8;

    [loginButton.layer insertSublayer:layer atIndex:0];

    return loginButton;
}

Do I need to handle the highlighting myself?

memmons
  • 40,222
  • 21
  • 149
  • 183
Padin215
  • 7,444
  • 13
  • 65
  • 103

1 Answers1

5

Yes, you will need to handle highlighting yourself. Rather than rolling your own code though, you should check out Jeff Lamarche's incredibly easy to use iPhone Gradient Buttons Project. It does exactly what you are trying to do. It's just 2 files, so it's easy to incorporate into your project:

http://code.google.com/p/iphonegradientbuttons/source/browse/trunk/Classes/GradientButton.h http://code.google.com/p/iphonegradientbuttons/source/browse/trunk/Classes/GradientButton.m

Screenshot below taken from Jeff's Blog discussing the project.

Imageless gradient buttons

memmons
  • 40,222
  • 21
  • 149
  • 183