How to detect if the image of UIImageView has changed

时间:2015-07-31 20:18:49

标签: ios uiimageview uiactivityindicatorview

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! :)

3 个答案:

答案 0 :(得分:11)

如果您正在使用swift,您还可以创建UIImageView子类并覆盖image属性以使用didSet观察值。只记得设置超类的图像。

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

答案 1 :(得分:1)

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");
  }
}

答案 2 :(得分:0)

1- 创建一个 NSKeyValueObservation 属性

2- 使用 yourImageView.observe...

初始化 viewDidLoad 中的属性

3- 设置它以便它侦听 \.image 并将选项设置为 [.old, .new]

4- 移除 deinit 中的观察者

@IBOutlet var yourImageView: UIImageView!

var observer: NSKeyValueObservation? // 1.

override func viewDidLoad() {
    super.viewDidLoad()

    observer = nil // not necessary but still

    // 2.                            // 3.
    observer = yourImageView.observe(\.image, options: [.old, .new], changeHandler: { [weak self](imageView,_) in
            
        guard let img = imageView.image else { return }

        print("an image was set on your imageView, do something with the image", img)
    })
}

deinit {

    observer = nil // 4.
}