How to determine if UIImageView image has changed

I have an application where a user can select an image from a camera roll and that image is loaded into UIImageView

. However, if the image is large, there is a delay until the selected image appears in UIImageView

(no image adjustment is made to main thread

, so the UI will not be frozen). Until the image is set, I would like to show an activity indicator that notifies the user that the application is not freezing by simply loading the image. However, I don't know how to detect when the image is set UIImageView

to hide the activity indicator. I guess KVO can help here, but I'm not sure how to implement it correctly.

Sorry for the noob question! :)

+3


source to share


2 answers


Observe image property of UIImageView with KVO. Add code to stop spinner instead 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");
  }
}

      

+1


source


If you are using swift, you can also subclass UIImageView

and override the property image

to observe values ​​with didSet

. Just remember to install the superclass image.



class ImageView: UIImageView {
    override var image: UIImage? {
        didSet {
            super.image = image
            println("Image Set")
        }
    }
}

      

+8


source







All Articles