设置图像属性后,UIImageView图像无法明显更新 [英] UIImageView image does not update visibly when image property is set

查看:207
本文介绍了设置图像属性后,UIImageView图像无法明显更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UIImageView,其用户交互为true,并为其提供了轻击手势识别器,其动作处理程序如下:

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.

此外,如果我随后继续将图像视图的图像替换为 图像,则会看到 red 图像!

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图像无法明显更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆