How do you change UIButton image alpha on disabled state?

后端 未结 11 2199
庸人自扰
庸人自扰 2021-02-03 23:22

I have a UIButton with an image and on its disabled state, this image should have .3 alpha.

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIIm         


        
相关标签:
11条回答
  • 2021-02-04 00:14

    The button’s image view. (read-only)

    @property(nonatomic, readonly, retain) UIImageView *imageView
    

    Although this property is read-only, its own properties are read/write.

    0 讨论(0)
  • 2021-02-04 00:16

    Swift 3:

    extension UIImage {
        func copy(alpha: CGFloat) -> UIImage? {
            UIGraphicsBeginImageContextWithOptions(size, false, scale)
            draw(at: CGPoint.zero, blendMode: .normal, alpha: alpha)
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImage
        }
    }
    

    Usage:

    button.setImage(image.copy(alpha: 0.3), for: .disabled)
    
    0 讨论(0)
  • 2021-02-04 00:22

    I found that none of these solutions really work. The cleanest way of doing it is to subclass, and instead of using self.imageView, just add your own custom imageView like this:

    _customImageView = [[UIImageview alloc] initWithImage:image];
    

    Then add your custom alpha like so:

    - (void)setEnabled:(BOOL)enabled {
        [super setEnabled:enabled];
        if (enabled) {
            _customImageView.alpha = 1.0f;
        } else {
            _customImageView.alpha = 0.25f;
        }
    }
    
    0 讨论(0)
  • 2021-02-04 00:22

    Swift 5:

    Here's a solution that extends the UIButton class. No need to sub-class. In my example, button alpha is set to 0.55 if .isEnabled is false, and 1.0 if it's true.

    extension UIButton {

    override open var isEnabled: Bool{
        didSet {
            self.alpha = isEnabled ? 1.0 : 0.55
        }
    }
    

    }

    0 讨论(0)
  • 2021-02-04 00:23

    If setting alpha while the button is disabled doesn't work, then just make your disabled image at the alpha value you desire.

    Just tested this, you can set the alpha on the UIButton, regardless of state and it works just fine.

    self.yourButton.alpha = 0.25;
    
    0 讨论(0)
提交回复
热议问题