I have a UIButton with an image and on its disabled state, this image should have .3 alpha.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIIm
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.
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)
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;
}
}
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
}
}
}
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;