change the transform or select state will cause another problem, the best way is using category:
const char kNormalImage;
const char kSelectImage;
const char kDisableImage;
@interface UIButton ()
@property (nonatomic, strong) UIImage *normalImage;
@property (nonatomic, strong) UIImage *selectImage;
@property (nonatomic, strong) UIImage *disableImage;
@end
@implementation UIButton (Hidden)
- (void)setImageViewHidden:(BOOL)hidden {
if (hidden) {
self.normalImage = [self imageForState:UIControlStateNormal];
self.selectImage = [self imageForState:UIControlStateSelected];
self.disableImage = [self imageForState:UIControlStateDisabled];
UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, NO, 0.0);
UIImage *blank = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self setImage:blank forState:UIControlStateNormal];
[self setImage:blank forState:UIControlStateSelected];
[self setImage:blank forState:UIControlStateDisabled];
} else {
[self setImage:self.normalImage forState:UIControlStateNormal];
[self setImage:self.selectImage forState:UIControlStateSelected];
[self setImage:self.disableImage forState:UIControlStateDisabled];
}
}
- (UIImage *)normalImage {
return objc_getAssociatedObject(self, &kNormalImage);
}
- (void)setNormalImage:(UIImage *)normalImage {
objc_setAssociatedObject(self, &kNormalImage, normalImage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIImage *)selectImage {
return objc_getAssociatedObject(self, &kSelectImage);
}
- (void)setSelectImage:(UIImage *)selectImage {
objc_setAssociatedObject(self, &kSelectImage, selectImage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIImage *)disableImage {
return objc_getAssociatedObject(self, &kDisableImage);
}
- (void)setDisableImage:(UIImage *)disableImage {
objc_setAssociatedObject(self, &kDisableImage, disableImage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end