3

I am trying the following code to make a UIButton look Disabled :

btnYourButton.alpha = 0.6f;
btnYourButton.enabled = NO;

While making is enabled(and of course to look enabled)

btnYourButton.alpha = 1.0f;
btnYourButton.enabled = YES;

Isn't there any way, by which I can perform both of this (making UIButton disable/enable and also to make it look disable/enable) in a single statement ?

Krishna
  • 368
  • 5
  • 17

3 Answers3

4

Or you could try subclassing UIButton, something like:

file MyKindOfButton.h

#import <UIKit/UIKit.h>

@interface MyKindOfButton : UIButton

@end

file MyKindOfButton.m

#import "MyKindOfButton.h"

@implementation MyKindOfButton

- (void)setEnabled:(BOOL)enabled {

    [super setEnabled: enabled];

    if (enabled) {
        self.alpha = 1.0f;
    } else {
        self.alpha = 0.6f;

    }
}

@end
Rok Jarc
  • 18,765
  • 9
  • 69
  • 124
1

I know this is a very old question, but here is a very nice solution. Just create a category of UIColor and add this method.

+ (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)];
}

Now you can just set the backgroundImage to whatever color you want and it will automatically handle the disable appearance for you.

[button setTitleColor:[UIColor someColor] forState:UIControlStateNormal];
horsejockey
  • 817
  • 10
  • 18
0

Another option is to change the text color (to light gray for example) for the disabled state. In the storyboard editor, choose Disabled from the State Config popup button, and use the Text Color popup button to change the text color. In code, use the -setTitleColor:forState: message.

(I realize this is an older post, but I thought others might like this option)

guywithmazda
  • 757
  • 7
  • 10