如何在黑暗模式下快速将彩色渐变图像更改为白色

时间:2020-09-11 02:35:45

标签: ios swift gradient uicolor

我正在创建一个collectionview,我想过要在单元格中有一个图像,在浅色模式下具有渐变色,当它切换为暗色模式时,图像变为白色。我能够使它正常运行,但只能部分运行。

当我以灯光模式启动时,我的收藏视图如下:

enter image description here

这就是我想要的。当我使用Xcode中的切换将其更改为暗模式时,它的确会使图像变白: enter image description here

但是,我注意到的问题之一是并非单元格中的所有图像都会改变:

enter image description here

另一个问题是,当我以暗模式启动时,图像具有渐变颜色,这不是我想要的颜色:

enter image description here

正如您可以想象的那样,此时更改为灯光模式时图像为白色。

我认为我阅读了很多有关暗模式的文章,但似乎无法弄清楚自己在做什么错。 这些是我读过的文章:

我也看了很多其他人的帖子,但我对其中任何一个都没有任何运气:

我使用了几种方法尝试使其正常运行,但是它对我而言并不起作用。

var imageColor1 = UIColor()
    var imageColor2 = UIColor()    

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        
        if traitCollection.userInterfaceStyle == .dark {
            cellImg.image = imgView?.maskWithGradientColor(color1: .white, color2: .white)
            
        } else {
            cellImg.image = imgView?.maskWithGradientColor(color1: imageColor1, color2: imageColor2)
        }
    }

对于我来说,这并不是真正有效的方法。

func configure(with list: List) {
    cellName.text = list.name
    
    
    
    imageColor1 = UIColor(hexString: "#\(list.color1)")
    imageColor2 = UIColor(hexString: "#\(list.color2)")

    cellImg.image = imgView?.maskWithGradientColor(color1: imageColor1, color2: imageColor2)
}

我考虑过使用属性观察器尝试并使用变化的UIColor,如下所示:

var imageColor: UIColor? { 
   didSet { 
       //it is at this point i haven't been able to figure it out
       //imageColor1 = imageColor  causes a crash
   }
 }

最后,我认为问题在于我仅在检测到它何时更改,而不是其当前模式。另一个问题是,当我想要任何一个时,并非所有单元格都在变化。任何帮助表示赞赏。如果还有其他需要帮助的地方,请询问。 谢谢

0 个答案:

没有答案