iOS 深色模式的自定义提升背景颜色

Custom elevated background color for iOS dark mode

dark mode section of the Human Interface Guidelines 中,Apple 描述了当您使用系统背景时基本上有三种背景颜色 - 浅色、深色和深色升高(例如,用于模态)。

有什么方法可以将这种提升的样式用于自定义颜色吗?我的 Assets 文件中有一个自定义背景颜色,包括浅色和深色模式,但对于提升的内容,它仍将使用深色模式颜色。

感谢 Kurt Revis 将我指向 this。我能够使用 Swift 提供的特殊 UIColor 初始值设定项来做到这一点。唯一的缺点是这在界面生成器中不起作用(因为它没有融入资产本身),但在代码中它会完美地工作:

class ElevatedColor: UIColor {
    convenience init(regular: UIColor, elevated: UIColor) {
        if #available(iOS 13.0, *) {
            self.init { (traitCollection: UITraitCollection) -> UIColor in
                let isElevated = (traitCollection.userInterfaceLevel == .elevated)
                return isElevated ? elevated : regular
            }
        } else {
            self.init(cgColor: regular.cgColor)
        }
    }
}

这使用 UIColor.init(dynamicProvider:)。 iOS 将在界面特征发生变化时调用提供的块,因此在切换到提升的上下文时颜色会自动更新。不幸的是,由于 the way UIColor works,您只能将初始化器设为便利初始化器,因此从技术上讲,您可以创建没有提升版本的 ElevatedColor,但对我来说这是可以接受的。