UIImageView image does not update visibly when image property is set(设置图像属性时,UIImageView 图像不会明显更新)
问题描述
我有一个 UIImageView,它的用户交互是真实的,我给了一个点击手势识别器,它的动作处理程序如下:
I have a UIImageView whose user interaction is true and to which I have given a tap gesture recognizer, whose action handler is as follows:
@IBAction func tap(_ sender:UITapGestureRecognizer) {
let iv = sender.view as! UIImageView
let im = iv.image!
let im2 = UIGraphicsImageRenderer(size:im.size).image { _ in
UIColor.red.setFill()
UIBezierPath(rect: CGRect(origin:.zero, size:im.size)).fill()
}
iv.image = im2
}
我希望当我点击图像视图时显示的图像会被纯红色图像替换.这在我运行 Xcode 9.4 的 High Sierra 机器上运行良好.但在我运行 Xcode 9.2 的 Sierra MacBook 上,没有明显的反应.
I expect the image displayed, when I tap the image view, to be replaced by a solid red image. This works fine on my High Sierra machine running Xcode 9.4. But on my Sierra MacBook running Xcode 9.2, nothing visibly happens.
这很奇怪.通过在调试器中暂停,我可以看到新图像正在正确构建:
It's weird. By pausing in the debugger, I can see that the new image is being constructed correctly:
图像正在被替换,但图像视图没有被重绘.添加像 setNeedsDisplay
这样的调用没有任何作用.
The image is being replaced, but the image view isn't being redrawn. Adding calls like setNeedsDisplay
does nothing.
此外,如果我随后将图像视图的图像替换为 不同 图像,我会看到 红色 图像!
Moreover, if I then proceed to replace the image view's image with a different image, I see the red image!
iv.image = im2
delay(0.5) {
iv.image = im // causes im2 to appear!
}
某种幕后缓存显然会导致图像视图在其显示中落后一个图像.
Some sort of behind-the-scenes caching is evidently causing the image view to get behind in its display by one image.
有人能解释一下吗?这可能是 iOS 本身的一个错误,特别是在 9.2 中;如何解决它?(显然,我们可以批量替换另一个图像视图,但这并不能告诉我们缓存发生了什么.)
Can anyone shed light on this? It's presumably a bug in iOS itself, and perhaps in 9.2 specifically; how would one work around it? (Obviously one could substitute another image view wholesale, but that wouldn't tell us what's going on with the caching.)
推荐答案
这似乎是一种解决方法:
This seems to be a workaround:
iv.image = im2
delay(0.05) {
iv.image = nil
iv.image = im2
}
但是太可怕了...省略任何这些分配,或将 delay
减少到零(例如,通过调用 DispatchQueue.main.async
代替),导致解决方法失败.
But what a horror... Omitting any of those assignments, or reducing the delay
to zero (e.g. by calling DispatchQueue.main.async
instead), causes the workaround to fail.
这篇关于设置图像属性时,UIImageView 图像不会明显更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:设置图像属性时,UIImageView 图像不会明显更新


- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01