首页 > 基础资料 博客日记

UIImageView 设置图片不生效的原因排查

2026-04-18 21:00:02基础资料围观1

文章UIImageView 设置图片不生效的原因排查分享给大家,欢迎收藏极客资料网,专注分享技术知识

最近在项目中碰到了一个UIImageView的问题。

需求内容是无论是在浅色还是深色模式,UIImageView都使用深色模式下的图片。

最先想到的方法就是从Image Assets中按照下面方法取出对应的深色模式图片,然后赋值给UIImageViewimage属性:

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.imageconfiguration属性输出可以看到,图片的UserInterfaceStyle还是Light

通过调试UIImageViewsetImage:方法,发现内部会调用下面的方法:

-[UIImageView _resolveImagesWithPreviouslyDisplayedImage:]:

_resolveImagesWithPreviouslyDisplayedImage:方法会获取UIImageView当前的traitCollection:

0x19b688834 <+108>: bl     0x199d49170 ; -[UIImageView _effectiveImageViewTraitCollectionForResolvingImages]

lldb输出可以看到,UIImageViewUserInterfaceStyleLight:

(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>

接着会比较UIImageViewtraitCollection和要设置的图片的traitCollection是否相等:

0x19b68884c <+132>: bl     0x19ad03818  ; -[UITraitCollection _isEqualToTraitCollectionForResolvingImage:]

只有两者相等,设置的图片才生效。

这里由于UIImageViewUserInterfaceStyleLight,而要设置的图片的UserInterfaceStyleDark,因此二者不相等。

在二者不相等的情况下,UIImageView会使用自己的traitCollectionImage Assets中找对应的图片:

 0x19b68898c <+452>: bl     0x19b68858c  ; -[UIImageView _resolvedImageFromImage:withImageViewTrait:]

由于UIImageViewUserInterfaceStyleLight,因此找到的也是Light图片。

最后UIImageView会将找到的图片设置为真正要显示的图片。

这就是为什么使用暗黑模式的图片设置UIImageViewimage属性不成功的原因。

知道了原因,想要解决,就只需要将保证UIImageViewUserInterfaceStyle和要设置的图片一样即可。

imageView.overrideUserInterfaceStyle = .dark

加上上面代码,UIImageView就可以正常显示暗黑模式的图片了。

实际上,设置了UIImageViewoverrideUserInterfaceStyle属性为dark,即使不设置UIImageViewimage属性为暗黑模式图片,系统也会自动切换到暗黑模式图片。


文章来源:https://www.cnblogs.com/chaoguo1234/p/19888978
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云