iosuiimageviewuiactivityindicatorview

How to detect if the image of UIImageView has changed


I have an app where the user can choose an image from the camera roll and than that image is loaded into an UIImageView. However, if the image is big there is a delay till the selected image actually appears in the UIImageView (Setting the image is not performed on the main thread so the UI does not get frozen). Until the image is set, I would like to show an activity indicator which notifies the user that the app did not freeze, its just loading the image. However I don't know how to detect when the image got set in the UIImageView to hide the activity indicator. I am guessing maybe KVO could help here, but I am not sure how to implement it properly.

Sorry for the noob question! :)


Solution

  • Observe UIImageView image property using KVO. Add code to stop spinner in place of NSLog(@"imageReady");.

    @implementation ViewController {
       __weak IBOutlet UIImageView *_imageView;
    }
    
    - (void)viewDidLoad {
       [super viewDidLoad];
       // Do any additional setup after loading the view, typically from a nib.
       [_imageView addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionNew context:NULL];
    }
    
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
      if ([keyPath isEqualToString:@"image"]) {
         //Image ready
         //Stop loading spinner.
         NSLog(@"imageReady");
      }
    }