Andy A
Andy A

Reputation: 4301

Disabled UIButton not faded or grey

In my iPhone app, I have a UIButton which I have created in Interface Builder. I can successfully enable and disable it like this in my code ...

sendButton.enabled = YES;

or

sendButton.enabled = NO;

However, the visual look of the button is always the same! It is not faded or grey. If I attempt to click it though, it is enabled or disabled as expected. Am I missing something? Shouldn't it look faded or grey?

Upvotes: 165

Views: 133638

Answers (19)

Rashid Latif
Rashid Latif

Reputation: 2901

Swift 4+

extension UIButton {
    override open var isEnabled: Bool {
        didSet {
            if self.isEnabled {
                self.alpha = 1.0
            }
            else {
                self.alpha = 0.5
            }
            //make sure button is updated
            self.layoutIfNeeded()
        }
    }
}

How to use

myButton.isEnabled = false

Upvotes: 9

Li Jin
Li Jin

Reputation: 2147

It looks like the following code works fine. But in some cases, this doesn't work.

sendButton.enabled = NO;
sendButton.alpha = 0.5;

If the above code doesn't work, please wrap it in Main Thread. so

dispatch_async(dispatch_get_main_queue(), ^{
    sendButton.enabled = NO;
    sendButton.alpha = 0.5
});

if you go with swift, like this

DispatchQueue.main.async {
    sendButton.isEnabled = false
    sendButton.alpha = 0.5
}

In addition, here I write UIButton extension functions.

extension UIButton {
    func enable() {
        DispatchQueue.main.async {
            self.isEnabled = true
            self.alpha = 1.0
        }
    }

    func disable() {
        DispatchQueue.main.async {
            self.isEnabled = false
            self.alpha = 0.5
        }
    }
}

Thank you and enjoy coding!!!

Upvotes: 3

Jaya Mayu
Jaya Mayu

Reputation: 17247

Maybe you can subclass your button and override your isEnabled variable. The advantage is that you can reuse in multiple places.

override var isEnabled: Bool {
     didSet {
         if isEnabled {
             self.alpha = 1
         } else {
             self.alpha = 0.2
         }
     }
 }

Upvotes: 2

ChavirA
ChavirA

Reputation: 707

You can use the both first answers and is going to be a better result.

In the attribute inspector (when you're selecting the button), change the State Config to Disabled to set the new Image that is going to appear when it is disabled (remove the marker in the Content->Enabled check to made it disabled).

And when you change the state to enabled, the image will load the one from this state.

Adding the alpha logic to this is a good detail.

Upvotes: 4

iosMentalist
iosMentalist

Reputation: 3084

Create an extension in Swift > 3.0 rather than each button by itself

extension UIButton {
    override open var isEnabled : Bool {
        willSet{
            if newValue == false {
                self.setTitleColor(UIColor.gray, for: UIControlState.disabled)
            }
        }
    }
}

Upvotes: 4

guywithmazda
guywithmazda

Reputation: 767

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. Use the Text Color popup button to change the text color.

In code, use the -setTitleColor:forState: message.

Upvotes: 51

AechoLiu
AechoLiu

Reputation: 18368

If the UIButton is in the combined state of selected and disabled, its state is UIControlStateSelected | UIControlStateDisabled.

So its state needs to be adjusted like this:

[button setTitleColor:color UIControlStateSelected | UIControlStateDisabled];
[button setImage:image forState:UIControlStateSelected | UIControlStateDisabled];

One approach is to subclass UIButton as follows:

@implementation TTButton
- (void)awakeFromNib {
   [super awakeFromNib];

    //! Fix behavior when `disabled && selected`
    //! Load settings in `xib` or `storyboard`, and apply it again.
    UIColor *color = [self titleColorForState:UIControlStateDisabled];
    [self setTitleColor:color forState:UIControlStateDisabled];

    UIImage *img = [self imageForState:UIControlStateDisabled];
    [self setImage:img forState:UIControlStateDisabled];
}

- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state {
    [super setTitleColor:color forState:state];

    //
    if (UIControlStateDisabled == state) {
        [super setTitleColor:color forState:UIControlStateSelected | state];
        [super setTitleColor:color forState:UIControlStateHighlighted | state];
    }
}

- (void)setImage:(UIImage *)image forState:(UIControlState)state {
    [super setImage:image forState:state];

    if (UIControlStateDisabled == state) {
        [super setImage:image forState:UIControlStateSelected | state];
        [super setImage:image forState:UIControlStateHighlighted | state];
    }
}

@end

Upvotes: 2

Kiran S
Kiran S

Reputation: 423

Set title color for different states:

@IBOutlet weak var loginButton: UIButton! {
        didSet {
            loginButton.setTitleColor(UIColor.init(white: 1, alpha: 0.3), for: .disabled)
            loginButton.setTitleColor(UIColor.init(white: 1, alpha: 1), for: .normal)
        }
    }

Usage: (text color will get change automatically)

loginButton.isEnabled = false

enter image description here

Upvotes: 10

oroom
oroom

Reputation: 1398

This question has a lot of answers but all they looks not very useful in case if you really want to use backgroundColor to style your buttons. UIButton has nice option to set different images for different control states but there is not same feature for background colors. So one of solutions is to add extension which will generate images from color and apply them to button.

extension UIButton {
  private func image(withColor color: UIColor) -> UIImage? {
    let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()

    context?.setFillColor(color.cgColor)
    context?.fill(rect)

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image
  }

  func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
    self.setBackgroundImage(image(withColor: color), for: state)
  }
}

Only one issue with this solution -- this change won't be applied to buttons created in storyboard. As for me it's not an issue because I prefer to style UI from code. If you want to use storyboards then some additional magic with @IBInspectable needed.

Second option is subclassing but I prefer to avoid this.

Upvotes: 1

Heo Đất Hades
Heo Đất Hades

Reputation: 1633

To make the button is faded when disable, you can set alpha for it. There are two options for you:

First way: If you want to apply for all your buttons in your app, so you can write extension for UIButton like this:

extension UIButton {

    open override var isEnabled: Bool{
        didSet {
            alpha = isEnabled ? 1.0 : 0.5
        }
    }

}

Second way: If you just want to apply for some buttons in your app, so you can write a custom class from UIButton like below and use this class for which you want to apply:

class MyButton: UIButton {
    override var isEnabled: Bool {
        didSet {
            alpha = isEnabled ? 1.0 : 0.5
        }
    }
}

Upvotes: 35

Ahmed R.
Ahmed R.

Reputation: 1229

just change state config to disable and choose what you want, background Image for disabled state

enter image description here

Upvotes: 88

Diego A. Rincon
Diego A. Rincon

Reputation: 768

This is quite an old question but there's a much simple way of achieving this.

myButton.userInteractionEnabled = false

This will only disable any touch gestures without changing the appearance of the button

Upvotes: 9

Yichao Lu
Yichao Lu

Reputation: 53

I am stuck on the same problem. Setting alpha is not what I want.

UIButton has "background image" and "background color". For image, UIButton has a property as

@property (nonatomic) BOOL adjustsImageWhenDisabled

And background image is drawn lighter when the button is disabled. For background color, setting alpha, Ravin's solution, works fine.

First, you have to check whether you have unchecked "disabled adjusts image" box under Utilities-Attributes.
Then, check the background color for this button.

(Hope it's helpful. This is an old post; things might have changed in Xcode).

Upvotes: 2

Mahesh Lad
Mahesh Lad

Reputation: 169

You can use adjustsImageWhenDisabled which is property of UIButton
(@property (nonatomic) BOOL adjustsImageWhenDisabled)

Ex:

 Button.adjustsImageWhenDisabled = false

Upvotes: 14

Ravin
Ravin

Reputation: 8564

You can use following code:

sendButton.enabled = YES;
sendButton.alpha = 1.0;

or

sendButton.enabled = NO;
sendButton.alpha = 0.5;

Upvotes: 219

user4179639
user4179639

Reputation:

#import "UIButton+My.h"
#import <QuartzCore/QuartzCore.h>
@implementation UIButton (My)


-(void)fade :(BOOL)enable{
    self.enabled=enable;//
    self.alpha=enable?1.0:0.5;
}

@end

.h:

#import <UIKit/UIKit.h>
@interface UIButton (My)

-(void)fade :(BOOL)enable;

@end

Upvotes: -1

King-Wizard
King-Wizard

Reputation: 15694

In Swift:

previousCustomButton.enabled = false
previousCustomButton.alpha = 0.5

or

nextCustomButton.enabled = true
nextCustomButton.alpha = 1.0

Upvotes: 6

Antonio Moro
Antonio Moro

Reputation: 152

If you use a text button, you can put into viewDidLoad the instance method

- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state

example:

[self.syncImagesButton setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];

Upvotes: 14

Jhaliya - Praveen Sharma
Jhaliya - Praveen Sharma

Reputation: 31722

Try to set the different images for UIControlStateDisabled (disabled gray image) and UIControlStateNormal(Normal image) so the button generate the disabled state for you.

Upvotes: 23

Related Questions