首页 > 基础资料 博客日记
UIImageView 设置图片不生效的原因排查
2026-04-18 21:00:02基础资料围观1次
最近在项目中碰到了一个UIImageView的问题。
需求内容是无论是在浅色还是深色模式,UIImageView都使用深色模式下的图片。
最先想到的方法就是从Image Assets中按照下面方法取出对应的深色模式图片,然后赋值给UIImageView的image属性:

var darkTrait = UITraitCollection(userInterfaceStyle: .dark)
// 取出暗黑模式下图片
let image = UIImage(named: name, in: nil, compatibleWith: darkTrait)
imageView.image = image
但是在浅色模式下,UIImageView还是显示浅色模式下的图片。
// 打印 image
(lldb) po imageView.image
▿ Optional<UIImage>
- some : <UIImage:0x30ac59cc0 named(main: BDPPersonalPage_video_collection) {16, 16} renderingMode=automatic(original)>
// 打印 image 的 configuration
(lldb) expression -l objc -O -- [0x30ac59cc0 configuration]
0x0000000301439a00
// 打印 configuration 的内容
(lldb) expression -l objc -O -- 0x0000000301439a00
<UIImageConfiguration:0x301439a00 traits=(UserInterfaceIdiom = Pad, DisplayScale = 2, DisplayGamut = P3, HorizontalSizeClass = Regular, VerticalSizeClass = Regular, UserInterfaceStyle = Light, UserInterfaceLayoutDirection = LTR, PreferredContentSizeCategory = L, AccessibilityContrast = Normal)>
从上面imageView.image的configuration属性输出可以看到,图片的UserInterfaceStyle还是Light。
通过调试UIImageView的setImage:方法,发现内部会调用下面的方法:
-[UIImageView _resolveImagesWithPreviouslyDisplayedImage:]:
_resolveImagesWithPreviouslyDisplayedImage:方法会获取UIImageView当前的traitCollection:
0x19b688834 <+108>: bl 0x199d49170 ; -[UIImageView _effectiveImageViewTraitCollectionForResolvingImages]
在lldb输出可以看到,UIImageView的UserInterfaceStyle是Light:
(lldb) po $x0
<UITraitCollection: 0x17c7fa1c0; UserInterfaceIdiom = Pad, DisplayScale = 2, DisplayGamut = P3, HorizontalSizeClass = Regular, VerticalSizeClass = Regular, UserInterfaceStyle = Light, UserInterfaceLayoutDirection = LTR, ForceTouchCapability = Unavailable, PreferredContentSizeCategory = L, AccessibilityContrast = Normal, UserInterfaceLevel = Base, HDRHeadroomUsageLimit = 1, SceneCaptureState = 0, ImageDynamicRange = 1>
接着会比较UIImageView的traitCollection和要设置的图片的traitCollection是否相等:
0x19b68884c <+132>: bl 0x19ad03818 ; -[UITraitCollection _isEqualToTraitCollectionForResolvingImage:]
只有两者相等,设置的图片才生效。
这里由于UIImageView的UserInterfaceStyle为Light,而要设置的图片的UserInterfaceStyle为Dark,因此二者不相等。
在二者不相等的情况下,UIImageView会使用自己的traitCollection从Image Assets中找对应的图片:
0x19b68898c <+452>: bl 0x19b68858c ; -[UIImageView _resolvedImageFromImage:withImageViewTrait:]
由于UIImageView的UserInterfaceStyle是Light,因此找到的也是Light图片。
最后UIImageView会将找到的图片设置为真正要显示的图片。
这就是为什么使用暗黑模式的图片设置UIImageView的image属性不成功的原因。
知道了原因,想要解决,就只需要将保证UIImageView的UserInterfaceStyle和要设置的图片一样即可。
imageView.overrideUserInterfaceStyle = .dark
加上上面代码,UIImageView就可以正常显示暗黑模式的图片了。
实际上,设置了UIImageView的overrideUserInterfaceStyle属性为dark,即使不设置UIImageView的image属性为暗黑模式图片,系统也会自动切换到暗黑模式图片。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签:

