在我的几个应用程序中,我有一个图像覆盖背景中的 View 。在我的 Assets 目录中,我的图像有任意、浅色和深色变化。在 iOS 13 中,当我启动应用程序时,会根据模式设置显示正确的浅色或深色模式图像。但是,当我在应用程序运行时切换模式时,图像不会改变。所有控件的所有其他属性(颜色等)都会发生变化,但图像不会。 我在 traitCollectiosnDidChange block 内尝试了以下 layoutIfNeeded() 和/或 layoutSubviews() :
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard let previousTraitCollection = previousTraitCollection else {return}
if #available(iOS 13.0, *) {
if previousTraitCollection.hasDifferentColorAppearance(comparedTo: traitCollection) {
print("Changed mode")
self.view.layoutIfNeeded()
self.view.layoutSubviews()
}
}
}
并且确实触发了 Change 模式,但布局没有改变。 有没有办法确保图像也显示正确的图像?
最佳答案
好的。回答我自己的问题。我正在将 .withHorizontallyFlippedOrientation() 应用于我的图像并将其设置在 ViewDidLoad 中。当我更改特征颜色模式时,此图像没有发生变化。 解决方案是在 differentColorAppearance 触发时重置图像和翻转属性。像这样
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard let previousTraitCollection = previousTraitCollection else {return}
if #available(iOS 13.0, *) {
if previousTraitCollection.hasDifferentColorAppearance(comparedTo: traitCollection) {
image2.image = UIImage(named: "CourseImage")?.withHorizontallyFlippedOrientation()
}
}
}
关于swift - 图像和暗模式不切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57960637/