You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SwiftUI中定义类似系统Primary Color的自定义动态主色?

解决方案

方案1:全版本兼容(iOS13+/macOS10.15+)

通过桥接UIKit/AppKit的动态颜色构造器实现,不依赖高版本SwiftUI API,适配所有支持SwiftUI的系统版本:

import SwiftUI

#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
typealias DynamicColor = UIColor
#elseif os(macOS)
import AppKit
typealias DynamicColor = NSColor
#endif

extension Color {
    static let customPrimary: Color = {
        let dynamicColor = DynamicColor { traitCollection in
            #if os(iOS) || os(tvOS) || os(watchOS)
            let isLight = traitCollection.userInterfaceStyle == .light
            #elseif os(macOS)
            let isLight = traitCollection.bestMatch(from: [.aqua, .darkAqua]) == .aqua
            #endif
            return isLight ?
            DynamicColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1) :
            DynamicColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1)
        }
        return Color(dynamicColor)
    }()
}

方案2:纯SwiftUI高版本实现(iOS17+/macOS14+)

如果你的App最低支持版本可以升到iOS17/macOS14,可以直接用SwiftUI原生的动态颜色构造器,无需桥接UIKit/AppKit:

import SwiftUI

extension Color {
    static let customPrimary = Color(
        light: Color(red: 0.1, green: 0.1, blue: 0.1),
        dark: Color(red: 0.95, green: 0.95, blue: 0.95)
    )
}

使用效果

两种方案定义的customPrimary都可以直接和系统内置的Color.primary一样使用,自动适配深浅模式,不需要读取环境变量或者封装为View,你原来的代码可以简化为:

struct ContentView: View {
    var body: some View {
        Color.customPrimary
            .frame(width: 100, height: 100)
            .cornerRadius(10)
        Color.primary
            .frame(width: 100, height: 100)
            .cornerRadius(10)
    }
}

内容的提问来源于stack exchange,提问作者swiftPunk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 09:45:00