ios 如何检测UIImageView更改或KVO在UIImageView上工作?

qcbq4gxm  于 2023-03-31  发布在  iOS
关注(0)|答案(2)|浏览(143)

我正在检测UIImageViewUIImage)改变了或没有使用键值观察器或任何其他可能的方法。我的图像视图在第一次加载时有一个图像,所以它不是image.image != nil。我使用UIPickerController,所以当我选择一个图像时,值会改变。我想检测这种变化,这样我就可以运行一些代码。例如,更改按钮的颜色或启用它。

btn.backgroundColor = UIColor.green
btn.isEnabled = true

我试着用这种方式添加一个观察者,但什么也没发生。没有打印输出,没有断点。

let driverPImg: UIImageView = {
    let image = UIImageView(image: #imageLiteral(resourceName: "DriverPimg"))
    image.layer.cornerRadius = 75
    image.clipsToBounds = true
    image.contentMode = .scaleAspectFill
    image.isUserInteractionEnabled = true
    image.translatesAutoresizingMaskIntoConstraints = false
    return image
}()

let key1: String = "key1"

        // in ViewDidLoad
override func viewDidLoad() {
    super.viewDidLoad()
    
    self.ProfileImg.image!.addObserver(self, forKeyPath: key1, options: .new, context: nil)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == key1 {
        print("not changed")
    } else {
        print("it did changed")
    }
}
z8dt9xmd

z8dt9xmd1#

  1. UIImageView子类
    1.覆盖image属性
    1.对didSet方法进行了一些判断
class SUIImageView: UIImageView {
    open var didSetImageBlock: ((_ image: UIImage?) -> Void)?
    open override var image: UIImage? {
        didSet {
            print("did Set image")
            if let didSetImage = didSetImageBlock {
                didSetImage(image)
            }
        }
    }
}

let driverPImg: SUIImageView = {
    let image =  let image = SUIImageView(image: #imageLiteral(resourceName: "DriverPimg"))
    image.layer.cornerRadius = 75
    image.clipsToBounds = true
    image.contentMode = .scaleAspectFill
    image.isUserInteractionEnabled = true
    image.translatesAutoresizingMaskIntoConstraints = false
    return image
}()

// Set the placeholder image before `didSetImageBlock` . So the first time
// you set the placeholder image, `didSetImageBlock` won't be triggered. 
// After the `didSetImageBlock` is set, if the image of the ImageView is 
// changed, `didSetImageBlock` will be triggered. 
driverPImg.didSetImageBlock = { (image: UIImage?) in
    //
    print("did Set Image Block")
}

如果您还想使用KVO,最好先阅读此文档。

l7wslrjt

l7wslrjt2#

没有人真正回答KVO的问题。
请参阅这些文档了解更多信息:https://developer.apple.com/documentation/swift/using-key-value-observing-in-swift

class MyView: UIView {

    // The @objc part is needed for KVO to work
    @objc private var imageView: UIImageView

    // KVO
    private var imageViewObservation: NSKeyValueObservation?

    init() {
        super.init()

        self.imageViewObservation = observe(\.imageView.image) { [weak self] _, _ in
            // image view changed
        }

    }
}

相关问题