[ios] 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?

This question is related to ios iphone cocoa-touch uibutton

The answer is


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.


#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

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

Ex:

 Button.adjustsImageWhenDisabled = false

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.


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, if you customized UIButton, add this to the Button class.

override var isEnabled: Bool {
    didSet {
        DispatchQueue.main.async {
            if self.isEnabled {
                self.alpha = 1.0
            }
            else {
                self.alpha = 0.5
            }
        }
    }
}

Thank you and enjoy coding!!!


In Swift:

previousCustomButton.enabled = false
previousCustomButton.alpha = 0.5

or

nextCustomButton.enabled = true
nextCustomButton.alpha = 1.0

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
        }
    }
}

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


Swift 4+

extension UIButton {
    override open var isEnabled: Bool {
        didSet {
            DispatchQueue.main.async {
                if self.isEnabled {
                    self.alpha = 1.0
                }
                else {
                    self.alpha = 0.6
                }
            }
        }
    }
}

How to use

myButton.isEnabled = false


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).


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];

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


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.


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)
            }
        }
    }
}

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

enter image description here


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

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


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
         }
     }
 }

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to cocoa-touch

Include of non-modular header inside framework module Move textfield when keyboard appears swift Create space at the beginning of a UITextField Navigation bar with UIImage for title Generate a UUID on iOS from Swift How do I write a custom init for a UIView subclass in Swift? creating custom tableview cells in swift How would I create a UIAlertView in Swift? Get current NSDate in timestamp format How do you add an in-app purchase to an iOS application?

Examples related to uibutton

How to make a simple rounded button in Storyboard? How to set the title text color of UIButton? How can I make a button have a rounded border in Swift? How to change UIButton image in Swift Changing text of UIButton programmatically swift Disable a Button How to change font of UIButton with Swift Attach parameter to button.addTarget action in Swift Change button background color using swift language Make a UIButton programmatically in Swift