Michael Ochs Michael Ochs - 1 month ago 4x
iOS Question

UIButton's imageView property and hidden/alpha value

I have a UIButton that should display an activity indicator instead of an image in some situations. What I do at the moment is setting the hidden property of the button's imageView to YES and back. I also tried this with setting the alpha value to 0.0f and back to 1.0f.

This works until the state of the button changes. This resets the properties of the imageView and leads to hidden == NO and alpha == 1.0f.

Has anybody did something similar or has an idea how to hide the imageView of a button while the rest of it stays visible?


It is simple. Button have different states. Just set zero image for selected state and your image for normal state. When you want to display activity indicator set button state as selected and add indicator as button subview.

- (void)initializeButton {
    button = [[UIButton alloc] init];
    [button addTarget:self action:@selector(buttonDidClick:) forControlEvents:UIControlEventTouchUpInside];

    [button setImage:[[UIImage alloc] init] forState:UIControlStateSelected]; //zero image
    [button setImage:yourImage forState:UIControlStateSelected]; //your image

- (void)buttonDidClick:(UIButton *)button {
    button.selected = YES;
    /* Add yor activity indicator with some view tag or save reference to it */

Call next method when your activity is finished

- (void)finishActivityWithButton:(UIButton *)button {
    button.selected = NO;
    /* Remove your activity indicator from button */