【发布时间】:2020-10-06 05:59:47
【问题描述】:
我正在尝试检测 UIImageView (UIimage) 是否已更改或未使用 KeyValueObserver 或任何其他可能的方法,我的图像视图在第一次加载时有一个图像,所以它不是 image.image != nil
我正在使用 UIPickerController,所以当我选择图像时,值会发生变化,我想检测这种变化,以便我可以运行一些代码,例如 Ex:更改按钮的颜色或启用它
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")
}
}
【问题讨论】:
-
应该使用
image而不是key1?也就是说,您为什么要尝试观察图像视图的图像?这似乎是一件很奇怪的事情。 -
因为我不能这样做[stackoverflow.com/questions/64183657/…图像视图有一个占位符图像所以它不是零所以我无法检查它是否是@Sweeper
-
如何创建一个
UIImageView扩展并覆盖image属性?然后自定义willSet和didSet? -
你能用代码解释一下吗?我不知道你在说什么????说真的,我这辈子都没用过
did and willSet@RYZhengspan>
标签: ios swift xcode uiimageview key-value-observing