跳到主要内容

深色模式适配

问题

如何高效地适配 iOS 深色模式?

答案

适配方案

// 1. 使用语义化颜色
label.textColor = .label // 自动适配深浅色
view.backgroundColor = .systemBackground

// 2. Asset Catalog 自定义颜色
// 在 Assets.xcassets 中创建 Color Set,分别设置 Light / Dark 值
let brandColor = UIColor(named: "BrandPrimary")

// 3. 代码中适配
let color = UIColor { trait in
trait.userInterfaceStyle == .dark ? .white : .black
}

图片适配

// Asset Catalog 中为图片设置 Appearances = Any, Dark
// 或者代码判断
let iconName = traitCollection.userInterfaceStyle == .dark ? "icon_dark" : "icon_light"

SwiftUI 适配

struct ContentView: View {
@Environment(\.colorScheme) var colorScheme

var body: some View {
Text("Hello")
.foregroundColor(colorScheme == .dark ? .white : .black)
}
}

注意事项

要点说明
避免硬编码颜色.label.systemBackground 等语义色
测试切换模拟器 → Environment Overrides → Dark
CGColor 不自动适配layer.borderColor 需要在 traitCollectionDidChange 中更新
截图测试两种模式都截图验证

常见面试问题

Q1: traitCollectionDidChange 什么时候调用?

答案:当 UITraitCollection 发生变化时调用,包括深浅模式切换、设备旋转、Dynamic Type 变更等。在这里更新 CGColor、手动绘制的颜色等不自动响应 trait 变化的属性。

相关链接