简体   繁体   中英

How i detect changes image in a UIImageView in Swift iOS

I am using UIImageView In. my UIViewController . in my case, I want to do if my image view changes then let me know it was changed or not.

Use KVO .

class ViewController: UIViewController {
    
    @IBOutlet weak var imageView: UIImageView!
    
    private var imageChangeObservation: NSKeyValueObservation?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        imageChangeObservation = imageView.observe(\.image, options: [.new]) { [weak self] (object, change) in
            print("Image changed")
        }
    }
}

first you create new swift file and add this code

import UIKit
class CustomImageView: UIImageView{
    override var image: UIImage?{
        didSet{
            delegate?.didChangeImage()
        }
    }
    
    var delegate: ImageViewDelegate?
    
}

protocol ImageViewDelegate {
    func didChangeImage()
}

second: set the delegate in your view controller

class ImageViewController: UIViewController, ImageViewDelegate {

@IBOutlet weak var yourImageViewOutlet: CustomImageView!
    
    func didChangeImage() {
         print("This Is Working")
         print("Image Is Changed")
         // This is your function
         // this function will called if and only if yourImageViewOutle image is changed
    }

     override func viewDidLoad() {
          super.viewDidLoad()
          yourImageViewOutlet.delegate = self
     }

}

important: outlet from the storyboard, provide the custom class name to outlet. Otherwise it will not work. 点击打开图片

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM